Skip to main content
 首页 » 编程设计

python之为什么以下简单的 Python 3 strptime() 代码可以在 OSX 而不是 Linux 上运行

2024年08月12日30bjzhanghao

以下用于读取和验证 ISO8601 格式日期的代码在 python 3.7.4 OSX 上按预期工作。它在 Linux 上引发错误

Python 3.6.8 (default, Oct 14 2019, 21:22:53)  
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux 
Type "help", "copyright", "credits" or "license" for more information. 
>>> format_string = '%Y-%m-%dT%H:%M:%S%z' 
>>> from datetime import datetime 
>>> d = datetime.strptime('2019-11-05T00:00:00Z', format_string) 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
  File "/usr/lib64/python3.6/_strptime.py", line 565, in _strptime_datetime 
    tt, fraction = _strptime(data_string, format) 
  File "/usr/lib64/python3.6/_strptime.py", line 362, in _strptime 
    (data_string, format)) 
ValueError: time data '2019-11-05T00:00:00Z' does not match format '%Y-%m-%dT%H:%M:%S%z' 

在 OSX 下:

Python 3.7.4 (default, Jul  9 2019, 18:15:00)  
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> format_string = '%Y-%m-%dT%H:%M:%S%z' 
>>> from datetime import datetime 
>>> d = datetime.strptime('2019-11-05T00:00:00Z', format_string) 
>>> print(d) 
2019-11-05 00:00:00+00:00 

我看了this article这与 C 库调用有关,但 Python 应该是可移植的吗?

我尝试过的两个发行版(Red Hat 和 EC2 Linux)都有来自 yum 的 3.6.8,并且都给出了错误。肯定不会是版本差异吧?

请您参考如下方法:

我已经在 Python 3.6.8 和 Python 3.7.4 Conda 环境中测试了这个 OSX。这似乎是 Python 版本之间的差异。

这是因为在 Python 3.7 中添加了对在日期时间格式字符串末尾使用 'Z' 的支持。 'Z' 是 UTC 偏移量“+00:00”的别名,'%z' 指令中未添加对 UTC 偏移量中的冒号分隔符的支持直到 Python 3.7。

对于同时适用于 Python 3.6 和 3.7 的解决方案,不要使用 'Z',而是使用 '+0000' 这样日期时间字符串就变成了 '2019-11-05T00:00:00+0000'。

format_string = '%Y-%m-%dT%H:%M:%S%z' 
d = datetime.strptime('2019-11-05T00:00:00+0000', format_string) 

将在两个版本中工作。

如需进一步引用,请查看 the Python 3.7 datetime docs .