gpt4 book ai didi

使用pytz的python时区转换问题

转载 作者:太空宇宙 更新时间:2023-11-04 03:35:00 25 4
gpt4 key购买 nike

我正在使用 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: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 .

关于使用pytz的python时区转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29516408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com