python 使用 pytz 时区转换问题

python timezone conversion issues using pytz

我正在使用 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_35tzinfo=<DstTzInfo 'US/Eastern' EDT-1 day, 20:00:00 DST>eight_amtzinfo=<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:35AM 所以如果我在早上 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 偏移量。

如果您更改了一个已知的日期时间对象(这样得到的时间可能会有不同的 utc 偏移量),那么您应该调用 dt = tz.normalize(dt) 来获取正确的 tzinfo。参见 Localized times and date arithmetic

你们都很有帮助!所以我所做的就是制作类似

的东西
@staticmethod
def est_localize(datetime_object):
    # remove tzinfo
    new_datetime = datetime_object.replace(tzinfo=None)
    # finally, localize the datetime
    new_datetime = pytz.timezone('US/Eastern').localize(new_datetime)
    return new_datetime

以及我创建的每个日期时间对象,我将它们全部包装在 est_localize() 中,包括我必须使用 +timedelta()+relativedelta() 的对象。只要我将它们包装在 est_localize() 中,所有翻译都正确。谢谢大家!

eight_35 = datetime.now(pytz.timezone('US/Eastern')) # assume today's 8:35AM EST
eight_am = est_localize(datetime(eight_35.year, eight_35.month, eight_35.day, 8))