我正在寻找一种更清洁的方法来执行此操作。我目前的做法很痛苦。
我使用日期时间来帮助我自动获取查询时间。我有不同的需求,但我的主要需求是始终有一个日期时间指向昨天的下午6点,如果> 6pm,请给我当前的下午6点。
为清楚起见,这就是日期时间的外观。此外,数据库位于GMT中。那就是timedelta的来源。我用.format()填充日期时间
WHERE time> ='2018-11-26T00:00:00Z
之所以使用'0'+ str(day.hour / minute / second / month / day / day),是因为datetime.hour(如果小于10)不包含0开头。因此需要添加它才能使查询正常工作
这是我的代码:
now = datetime.datetime.now()
#time_6pm_yest is my start time
time_6pm_yest = now.replace(hour = 18, minute = 0, second = 0, microsecond = 0) - timedelta(days = 1) + timedelta(hours = 5)
#Timedelta+5 for GMT
end = now.replace(second = 0, microsecond = 0)
if now.hour > 18:
time_6pm_yest = time_6pm_yest + timedelta(1)
else:
pass
end = now.replace(second = 0, microsecond = 0)
if time_6pm_yest.hour < 10:
start_hour = '0' + str(time_6pm_yest.hour)
else:
start_hour = time_6pm_yest.hour
if time_6pm_yest.minute < 10:
start_minute = '0' + str(time_6pm_yest.minute)
else:
start_minute = time_6pm_yest.minute
if time_6pm_yest.second < 10:
start_second = '0' +str(time_6pm_yest.second)
else:
start_second = time_6pm_yest.second
if time_6pm_yest.day < 10:
start_day = '0' + str(time_6pm_yest.day)
else:
start_day = time_6pm_yest.day
if time_6pm_yest.month < 10:
start_month = '0' + str(time_6pm_yest.month)
else:
start_month = time_6pm_yest.month
if end.hour < 10:
end_hour = '0' +str(end.hour)
else:
end_hour = end.hour
if end.minute < 10:
end_minute = '0' + str(end.minute)
else:
end_minute = end.minute
if end.second < 10:
end_second = '0' +str(end.second)
else:
end_second = end.second
if end.day < 10:
end_day = '0' + str(end.day)
else:
end_day = end.day
if end.month < 10:
end_month = '0' + str(end.month)
else:
end_month = end.month