我有一些代码在同一个python版本的Ubuntu和MacOS编译器上莫名其妙地工作.欢迎任何解释或解决方法.
首先,在Ubuntu Python上进行设置.机器以UTC格式运行.在时间字符串中使用PST失败,但将PST更改为UTC它工作正常.
Python 2.7.3 (default, Sep 26 2013, 20:03:06) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from datetime import datetime >>> date_str = 'Thu Jan 1 00:32:36 PST 2015' >>> now = datetime.strptime(date_str, '%a %b %d %H:%M:%S %Z %Y') Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime (data_string, format)) ValueError: time data 'Thu Jan 1 00:32:36 PST 2015' does not match format '%a %b %d %H:%M:%S %Z %Y' >>> date_str = 'Thu Jan 1 00:32:36 UTC 2015' >>> now = datetime.strptime(date_str, '%a %b %d %H:%M:%S %Z %Y') >>>
现在在MacOS上(在PDT中运行),python不关心指定什么时区并且适用于任何时区:
Python 2.7.3 (v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from datetime import datetime >>> date_str = 'Thu Jan 1 00:32:36 GMT 2015' >>> now = datetime.strptime(date_str, '%a %b %d %H:%M:%S %Z %Y') >>>
GCC的版本是不同的,python 2.7.3的日期戳是不同的,但这似乎是非常简单的功能,不具备操作系统依赖性.
我看到像http://bugs.python.org/issue8957这样松散相关的bug .作为python.org上的错误报告,这更好吗?
文档说%Z本质上是特定于平台的:
对%Z指令的支持基于tzname中包含的值以及日光是否为真.因此,它是特定于平台的,除了识别始终已知的UTC和GMT(并且被认为是非夏令时时区).