问题描述
我正在尝试在美国东部标准时间打印当前时间,但是我的结果偏离了一个小时(与Google的最佳本地时间和纽约当地时间相比)。我试过同时使用 pytz
和 dateutil
:
I'm trying to print the current time in EST, but my results are off by one hour (when compared to Google's "est local time" and "nyc local time"). I've tried using both pytz
and dateutil
:
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"))))
我尝试研究正确的方法为此,以上就是我所发现的,但结果却不正确(例如,当Google表示上午11点时,它表示美国东部标准时间上午10点)。我的本地时间配置正确。我丢失了什么吗?
I've tried to research the correct way to do this, and the above is what I've found, yet the result is off (e.g. it shows 10 am EST when Google says it's 11 am). My local time is configured correctly. Am I missing something?
我正在使用:
- Python 3.8.5
- python-dateutil 2.8.1
- pytz 2020.1
推荐答案
您的时间减少一个小时,因为此时夏令时有效,并且当您指定 EST
时不会显示该时间。
Your time is off by an hour because daylight saving time is in effect at this time, and that is not represented when you specified EST
.
如问题注释中所述-您应使用基于地区的特定时区名称,例如 America / New_York
而不是 EST
。
As mentioned in the question's comments - you should use a specific locality-based time zone name, such as America/New_York
instead of EST
.
EST
在pytz和dateutil中都起作用的原因是它被定义为IANA时区名称:
The reason EST
works in both pytz and dateutil is that it is defined as an IANA time zone name:
发件人:
# 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
如您所见, EST
, MST
和 HST
是用固定偏移量定义的。他们没有遵守任何DST规则。没有 PST
或 CST
的类似条目,也没有类似 EDT的日光变体 code>。
As you can see, EST
, MST
, and HST
are defined with fixed offsets. They do not observe any DST rules. There are no similar entries for PST
or CST
, nor for daylight variants like EDT
.
名称类似于 EST5EDT
的区域向后兼容较早的POSIX样式的时区,但只有这些定义了4个。
The zones with names like EST5EDT
are backwards compatible with older POSIX-style time zones, but only these 4 are defined.
通常来说,您不应使用任何这些区域。他们只在那里当守卫。
Generally speaking, you should not use any of these zones. They are there for the guard only.
这篇关于Python时区:为什么EST会减少一小时? (pytz / dateutil)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!