datetime.strTime()接受%Z的哪些可能值?

2024-05-13 19:04:02 发布

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

Python的datetime.strptime()被记录为在%Z字段中支持时区。例如:

In [1]: datetime.strptime('2009-08-19 14:20:36 UTC', "%Y-%m-%d %H:%M:%S %Z")
Out[1]: datetime.datetime(2009, 8, 19, 14, 20, 36)

不过,“UTC”似乎是我唯一能支持它的时区:

In [2]: datetime.strptime('2009-08-19 14:20:36 EDT', "%Y-%m-%d %H:%M:%S %Z")
ValueError: time data '2009-08-19 14:20:36 EDT' does not match format '%Y-%m-%d %H:%M:%S %Z'

In [3]: datetime.strptime('2009-08-19 14:20:36 America/Phoenix', "%Y-%m-%d %H:%M:%S %Z")
ValueError: time data '2009-08-19 14:20:36 America/Phoenix' does not match format '%Y-%m-%d %H:%M:%S %Z'

In [4]: datetime.strptime('2009-08-19 14:20:36 -0700', "%Y-%m-%d %H:%M:%S %Z")
ValueError: time data '2009-08-19 14:20:36 -0700' does not match format '%Y-%m-%d %H:%M:%S %Z'

%Z需要什么格式?或者,如何表示UTC以外的时区?


Tags: informatdatadatetimetimematch记录not
2条回答

我猜它们是GMT,UTC,以及time.tzname中列出的任何东西。

>>> for t in time.tzname:
...     print t
...
Eastern Standard Time
Eastern Daylight Time
>>> datetime.strptime('2009-08-19 14:20:36 Eastern Standard Time', "%Y-%m-%d %H:%M:%S %Z")
datetime.datetime(2009, 8, 19, 14, 20, 36)
>>> datetime.strptime('2009-08-19 14:20:36 UTC', "%Y-%m-%d %H:%M:%S %Z")
datetime.datetime(2009, 8, 19, 14, 20, 36)
>>> datetime.strptime('2009-08-19 14:20:36 GMT', "%Y-%m-%d %H:%M:%S %Z")
datetime.datetime(2009, 8, 19, 14, 20, 36)

当然,这些设置是特定于机器的,您的设置很可能会有所不同。

这是来自time模块,但我几乎可以肯定它适用于datetime

Support for the %Z directive is based on the values contained in tzname and whether daylight is true. Because of this, it is platform-specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones).

https://docs.python.org/library/time.html

在我的系统上:

>>> import time
>>> time.tzname
('PST', 'PDT')

在datetime.strptime中使用除这些以外的任何内容都会导致异常。所以,看看你的机器上有什么。

相关问题 更多 >