Python时区:为什么东部标准时间缩短一小时?(pytz/dateutil)

2024-03-29 07:15:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用EST打印当前时间,但我的结果比谷歌的“EST当地时间”和“纽约当地时间”差了一个小时。我已经尝试使用了pytzdateutil

import datetime
import dateutil.tz
import pytz

# Correct
print(datetime.datetime.now())

# Correct
print(datetime.datetime.now(dateutil.tz.UTC))

# Off by one hour
print(str(datetime.datetime.now(dateutil.tz.gettz("EST"))))

# Off by one hour
print(str(pytz.utc.localize(datetime.datetime.utcnow()).astimezone(pytz.timezone("EST"))))

我试着研究正确的方法来做到这一点,上面是我发现的,但结果是错的(例如,当谷歌说是上午11点时,它显示美国东部时间上午10点)。我的本地时间配置正确。我错过什么了吗

我正在使用:

  • Python 3.8.5
  • python dateutil 2.8.1
  • pytz 2020.1

Tags: importdatetimeby时间onenowtzest
1条回答
网友
1楼 · 发布于 2024-03-29 07:15:21

由于夏令时在此时生效,因此您的时间缩短了一个小时,而在指定EST时,夏令时不表示夏令时

如问题评论中所述,您应该使用特定的基于位置的时区名称,例如America/New_York,而不是EST

EST在pytz和dateutil中工作的原因是它被定义为IANA时区名称:

发件人:https://github.com/eggert/tz/blob/2020a/northamerica#L188-L206

We generate the files specified below to guard against old files with obsolete information being left in the time zone binary directory. We limit the list to names that have appeared in previous versions of this time zone package...

# Zone  NAME     STDOFF  RULES  FORMAT  [UNTIL]
Zone    EST       -5:00  -      EST
Zone    MST       -7:00  -      MST
Zone    HST      -10:00  -      HST
Zone    EST5EDT   -5:00  US     E%sT
Zone    CST6CDT   -6:00  US     C%sT
Zone    MST7MDT   -7:00  US     M%sT
Zone    PST8PDT   -8:00  US     P%sT

如您所见,ESTMSTHST是用固定偏移量定义的。他们不遵守任何DST规则。对于PSTCST,以及类似EDT的日光变体,都没有类似的条目

名称为EST5EDT的区域向后兼容较旧的POSIX样式时区,但仅定义了这4个时区

一般来说,您不应该使用这些区域中的任何一个。他们在那里只是为了警卫

相关问题 更多 >