Source code for harp_apps.sqlalchemy_storage.utils.dates
fromsqlalchemyimportfuncfromsqlalchemy.ext.compilerimportcompilesfromsqlalchemy.sql.expressionimportColumnElementfromsqlalchemy.typesimportDateTime# Code from https://stackoverflow.com/questions/51662547/truncate-hour-day-week-month-year-in-sqlalchemy
[docs]@compiles(TruncDatetime,"mysql")defcompile_trunc_mysql(element,compiler,**kw):try:precision=element.precision.effective_valueexceptAttributeError:precision=element.precisionexpr=element.exprifprecision=="year":format_str="%Y-01-01 00:00:00"elifprecision=="month":format_str="%Y-%m-01 00:00:00"elifprecision=="day":format_str="%Y-%m-%d 00:00:00"elifprecision=="hour":format_str="%Y-%m-%d %H:00:00"elifprecision=="minute":format_str="%Y-%m-%d %H:%i:00"elifprecision=="second":format_str="%Y-%m-%d %H:%i:%s"else:raiseNotImplementedError(f"Truncating {precision} is not supported for MySQL")returncompiler.process(func.date_format(expr,format_str))
_modifiers={"year":("start of year",),"month":("start of month",),# This does not account for locale specific first day of week. 1 day# is added so that the 1st day of week won't truncate to previous week.# Replace 'weekday 0' with 'weekday 1', if you'd like first day of# week to be Monday (in accordance with ISO 8601)"week":("1 day","weekday 0","-7 days","start of day"),"day":("start of day",),}
[docs]@compiles(TruncDatetime,"sqlite")defcompile_trunc_sqlite(element,compiler,**kw):try:precision=element.precision.effective_valueexceptAttributeError:precision=element.precisionexpr=element.exprmodifiers=_modifiers.get(precision)ifmodifiers:returncompiler.process(func.datetime(expr,*modifiers))ifprecision=="hour":returncompiler.process(func.datetime(expr,func.strftime("-%M minutes",expr),func.strftime("-%f seconds",expr)))ifprecision=="minute":returncompiler.process(func.datetime(expr,func.strftime("-%f seconds",expr)))ifprecision=="second":returncompiler.process(func.datetime(expr,func.strftime("-%f seconds",expr),func.strftime("%S seconds",expr)))raiseNotImplementedError(f"Truncating {precision} is not supported for SQLite")