我正在使用 pytz 进行日期时间转换,但在美国东部标准时间上午 8 点左右活跃的情况下,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 点之后获取所有日志 处理它的最佳方法是什么,以便我可以检测到夏令时,但仍然能够准确地比较数据?
请您参考如下方法:
datetime.now(pytz.timezone('US/Eastern'))-- 正确datetime(..same time.., tzinfo=pytz.timezone('US/Eastern'))-- 不正确
参见 this answer为什么不应该将 tzinfo 参数与 pytz 时区一起使用,这些时区在不同时间可能具有不同的 utc 偏移量。
.now(tz) 在内部使用 UTC 时间 (tz.fromutc(utc_time)),因此它允许时区选择与给定的时间。
如果您更改了一个已知的日期时间对象(这样得到的时间可能具有不同的 utc 偏移量),那么您应该调用 dt = tz.normalize(dt) 来获取正确的 tzinfo。参见 Localized times and date arithmetic .
