Python: 从 strftime 打印时区

Python: print the time zone from strftime

我想打印时区。我使用 %Z 但它不打印:

import datetime
now = datetime.datetime.now()
print now.strftime("%d-%m-%Y")
print now.strftime("%d-%b-%Y")
print now.strftime("%a,%d-%b-%Y %I:%M:%S %Z") # %Z doesn't work

我是否需要导入 pytz

now() returns class datetime.datetime 的对象,它本身并不包含有关其时区的信息。 (即它是 "naive";参见 "naive" 与 "aware" 日期和时间对象 in the documentation 的描述)

根据documentation,

datetime.datetime.now(tz=None)

Return the current local date and time.

...

If optional argument tz is None or not specified, the timestamp is converted to the platform's local date and time, and the returned datetime object is naive.

要获取您平台的本地时区,您应该按照您的建议使用 pytz. Here's Alex Martelli's code to do this:

>>> import datetime
>>> now = datetime.datetime.now()
>>>
>>> from pytz import reference
>>> localtime = reference.LocalTimezone()
>>> localtime.tzname(now)
'Mountain Daylight Time'

您还可以获得实际的 UTC 偏移量,以小时为单位,通过:

>>> import time
>>> print(-time.timezone / 3600) # convert from seconds to hours
-7.0

所以你可以使用:

>>> print(now.strftime("%a, %d-%b-%Y %I:%M:%S, " + localtime.tzname(now)))
Wed, 08-Jul-2015 01:27:49, Mountain Daylight Time

这是记录在案的行为:datetime.now() returns 天真的日期时间对象和 %Z returns an empty string in such cases。您需要一个有意识的日期时间对象。

要打印本地时区缩写,您可以使用 tzlocal module that can return your local timezone as a pytz tzinfo object that may contain a historical timezone info e.g., from the tz database:

#!/usr/bin/env python
from datetime import datetime
import tzlocal # $ pip install tzlocal

now = datetime.now(tzlocal.get_localzone())
print(now.strftime('%Z'))
# -> MSK
print(now.tzname())
# -> MSK

此代码适用于时区 with/without 夏令时。它在 DST 转换前后和期间工作。即使 python 使用的 C 库无法访问给定平台上的历史时区数据库,如果本地时区在过去具有不同的 utc 偏移量,它也会起作用。


在Python 3.3+,当平台支持时,你可以使用.tm_zone attribute,得到tzname:

>>> import time
>>> time.localtime().tm_zone
'MSK'

或使用datetime模块:

>>> from datetime import datetime, timezone
>>> datetime.now(timezone.utc).astimezone().tzname()
'MSK'

代码是可移植的,但在某些平台上结果可能不正确(没有 .tm_zone(在这种情况下,datetime 必须使用 time.tzname)和 "interesting" timezones ).

在较旧的 Python 版本中,在具有 "uninteresting" 时区的系统上,您可以使用 time.tzname:

>>> import time
>>> is_dst = time.daylight and time.localtime().tm_isdst > 0
>>> time.tzname[is_dst]
'MSK'

"interesting" 时区的一个例子是 2010-2015 期间的 Europe/Moscow 时区。

Getting computer's UTC offset in Python 中讨论了类似的问题。

不应使用 pytz。来自帮助:

NAME
pytz.reference

DESCRIPTION
Reference tzinfo implementations from the Python docs.
Used for testing against as they are only correct for the years
1987 to 2006. Do not use these for real code.

对我来说最简单:

$ python3
>>> import datetime
>>> datetime.datetime.now().astimezone().strftime("%Y-%m-%dT%H:%M:%S %z")
>>> datetime.datetime.now().astimezone().strftime("%Y-%m-%dT%H:%M:%S %Z")
>>> exit()