【发布时间】:2021-03-31 15:20:30
【问题描述】:
这是非常出乎意料的行为...
-
我使用
'%c'指令创建了一个时间字符串。 -
然后我尝试解析生成的时间字符串,指定与字符串格式相同的
'%c'。 -
但是,正如您从下面的错误中看到的那样,这不起作用。我错过了什么?
我需要能够将时间存储在人类可读的本地化字符串中,然后将该字符串转换回struct_time,以便从中提取信息。
(字符串本地化非常重要,我当然不想为世界各地的所有语言环境编写解析算法!)
# Ensure the locale is set.
import locale
locale.setlocale(locale.LC_ALL, '')
'en_US.UTF-8'
# 1. Create a localized time string using the '%c' directive.
import datetime
time_stamp = datetime.datetime.now().strftime('%c')
time_stamp
'Mon 21 Dec 2020 03:47:55 PM '
# 2. Try to parse the string using the same directive used to create it.
import time
time.strptime(time_stamp, '%c')
# 3. Unexpected error...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.8/_strptime.py", line 562, in _strptime_time
tt = _strptime(data_string, format)[0]
File "/usr/lib/python3.8/_strptime.py", line 349, in _strptime
raise ValueError("time data %r does not match format %r" %
ValueError: time data 'Mon 21 Dec 2020 03:47:55 PM ' does not match format '%c'
【问题讨论】:
-
无法重现(在 Windows 上,Python 3.9)。
%c对我来说是双向的,无论我是使用我的默认语言环境还是设置另一个语言环境。
标签: python datetime time datetime-format