【发布时间】:2015-06-13 12:21:29
【问题描述】:
我正在使用 pytz 进行日期时间转换,但在大约 8 AM EST DST 活动的情况下,pytz 会显示意外数据。
eight_35 = datetime.now(pytz.timezone('US/Eastern')) # assume today's 8:35AM EST
eight_am = datetime(eight_35.year, eight_35.month, eight_35.day, 8, 0, 0, 0, tzinfo=pytz.timezone('US/Eastern'))
我注意到虽然eight_35 有tzinfo=<DstTzInfo 'US/Eastern' EDT-1 day, 20:00:00 DST> 而eight_am 有tzinfo=<DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>,但我不确定哪个是正确的。
如果我转换为 UTC,我会得到以下结果:
eight_35.astimezone(pytz.utc) >>> 12:35PM UTC
eight_am.astimezone(pytz.utc) >>> 12:56PM UTC
我的代码应该检查用户是否已经在美国东部标准时间上午 8 点之后登录。 Django 在创建查询集时会自动转换为 UTC。
UserLoginLog.objects.create(user=user, date_login=now) date logged is 12:35PM UTC
# this will result in no items because eight_am is translated as 12:56PM
UserLoginLog.objects.filter(user=user, date_login__gte=eight_am)
如您所见,用户在上午 8 点 35 分登录,所以如果我在上午 8 点之后获得所有日志 处理它的最佳方法是什么,以便我可以检测夏令时但仍然能够准确地比较数据?
【问题讨论】:
-
您可能会发现Problems with Localtime 很有帮助;它解释了为什么直接指定
tzinfo有时不起作用,以及如何使用localize解决问题。 -
您需要本地化或规范化日期时间。仅仅因为当您有一个幼稚的日期时间并应用时区时,此时没有关于夏令时的信息。一般来说,从本地
datetime转换为UTC 可能有两个结果。因此,正如@unutbu 评论的那样,在将时区应用于天真的datetime时,仅使用localize。
标签: python django python-3.x django-1.7 pytz