我试图从django查询集中获取明天发生的所有事件的列表。我假设我需要明天午夜到明天晚上11:59。我认为如果tomorrow_start设置为00:00:00,我的tomorrow_end变量将是正确的,目前它已获得确切的时间。
有人可以告诉我如何将下面的时间改为00:00:00吗?
tomorrow_start = timezone.now() + timedelta(1)
tomorrow_end = tomorrow_start + timedelta(hours=11,minutes=59)
maintenance = CircuitMaintenance.objects.filter(start_time__gte=tomorrow_start, end_time__lte=tomorrow_end)
答案 0 :(得分:2)
你也可以这样做:
import pytz
from datetime import datetime, timedelta
timezone = pytz.timezone('Europe/London')
dt_now = datetime.now(timezone)
tomorrow_start = datetime(dt_now.year, dt_now.month, dt_now.day, tzinfo=timezone) + timedelta(1)
tomorrow_end = tomorrow_start + timedelta(hours=12)
maintenance = CircuitMaintenance.objects.filter(start_time__gte=tomorrow_start, end_time__lt=tomorrow_end)
请注意,我们更改了查询,以便从开始时间开始不到12小时。这样您就可以从11:59:00到12:00:00捕获60秒。
来自ipython的示例输出:
In [1]: import pytz
...: from datetime import datetime, timedelta
...: timezone = pytz.timezone('Europe/London')
...: dt_now = datetime.now(timezone)
...: tomorrow_start = datetime(dt_now.year, dt_now.month, dt_now.day, tzinfo=timezone) + timedelta(1)
...: tomorrow_end = tomorrow_start + timedelta(hours=12)
...:
In [2]: print timezone
Europe/London
In [3]: print dt_now
2017-01-17 19:42:23.044706+00:00
In [4]: print tomorrow_start
2017-01-18 00:00:00-00:01
In [5]: print tomorrow_end
2017-01-18 12:00:00-00:01
答案 1 :(得分:0)
可能它看起来不是很优雅但你可以使用datetime.combine来获得明天的午夜:
from datetime import datetime, timedelta, time
tomorrow_start = datetime.combine(timezone.now().date(), time(0, 0)) + timedelta(1)