我有点惊讶pythondatetime
.isoformat()
函数没有返回正确的信息。当向 fromtimestamp() 方法提供时区时,该函数正确返回 ISO 8601 格式的字符串。但是,在计算结果时会忽略时区。观察:
13:29 msimsonnet:~$ python
Python 2.7.1 (r271:86832, Jan 26 2011, 13:56:46)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
Running with pythonstartup.py
>>> import pytz,datetime
>>> datetime.datetime.fromtimestamp(1303876413).isoformat()
'2011-04-26T23:53:33'
>>> ny = pytz.timezone('America/New_York')
>>> sf = pytz.timezone('America/Los_Angeles')
>>> datetime.datetime.fromtimestamp(1303876413,ny).isoformat()
'2011-04-26T23:53:33-04:00'
>>> datetime.datetime.fromtimestamp(1303876413,sf).isoformat()
'2011-04-26T20:53:33-07:00'
>>>
我在 EDT 中的计算机上运行它(格林威治标准时间为 -400)。时间 1303876413 实际上是 2011 年 4 月 26 日晚上 11:53:33,我第一次写这个问题的时候。请注意,在第一个示例中,只是请求.isoformat()
返回'2011-04-26T23:53:33'
,这是错误的——它应该返回'2011-04-26T23:53:33-04:00'
,因为它返回本地时间并且 Python 知道时区。第二个例子是正确的,但我在 NY 时区对象中卡住了。第三个例子是错误的 --- Python 保留了时区,但它没有相应地调整时间。
附录:
如果您阅读所有评论,您会发现我正在寻找的行为可以使用utcfromtimestamp
而不是fromtimestamp