【问题标题】:Datetime parsing error, wrong format?日期时间解析错误,格式错误?
【发布时间】:2018-06-18 19:35:12
【问题描述】:

我在 Python 3.6 中解析日期时间字符串时遇到了一些问题。关键代码是:

datetime.datetime.strptime("Jan 08, 2018 07:04 PM UTC", '%b %d, %Y %I:%M %p %Z')

还有堆栈跟踪:

  File "marquito.py", line 180, in start
    test_date = "" if test_date == "" else datetime.datetime.strptime(test_date + " UTC", "%b %d, %Y %I:%M %p %Z")
  File "/usr/lib/python3.6/_strptime.py", line 565, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "/usr/lib/python3.6/_strptime.py", line 362, in _strptime
    (data_string, format))
ValueError: time data 'Jan 08, 2018 07:04 PM UTC' does not match format '%b %d, %Y %I:%M %p %Z'

您发现代码有什么问题吗?

【问题讨论】:

  • 相同。我也无法在 3.6.2 上重现这个
  • 您确定test_date 变量的格式为"Jan 08, 2018 07:04 PM UTC" 吗?打印出来看看。
  • @ichantz:好吧,鉴于异常消息正好包含该字符串..

标签: python python-3.x datetime datetime-format


【解决方案1】:

%b区域设置相关的。您的系统设置为非英语或 C 语言环境,因此月份名称不匹配。

要查看当前语言环境中支持的月份名称,请运行:

>>> import calendar
>>> print([calendar.month_abbr[i].lower() for i in range(13)])

在解析英文月份名称之前,将您的语言环境设置回C 或英文。您只需为LC_TIME 类别执行此操作:

import locale
locale.setlocale(locale.LC_TIME, 'C')

例如,在西班牙语言环境中,您的日期无法解析:

>>> import datetime
>>> import calendar
>>> with calendar.different_locale('es_ES'):
...     print([calendar.month_abbr[i].lower() for i in range(13)])
...     datetime.datetime.strptime("Jan 08, 2018 07:04 PM UTC", '%b %d, %Y %I:%M %p %Z')
...
['', 'ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic']
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.6/_strptime.py", line 565, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.6/_strptime.py", line 362, in _strptime
    (data_string, format))
ValueError: time data 'Jan 08, 2018 07:04 PM UTC' does not match format '%b %d, %Y %I:%M %p %Z'

但在默认的C 语言环境中解析成功:

>>> with calendar.different_locale('C'):
...     print([calendar.month_abbr[i].lower() for i in range(13)])
...     datetime.datetime.strptime("Jan 08, 2018 07:04 PM UTC", '%b %d, %Y %I:%M %p %Z')
...
['', 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']
datetime.datetime(2018, 1, 8, 19, 4)

我使用 未记录的内部 calendar.different_locale() 上下文管理器临时更改 LC_TIME 区域设置。它在进入上下文时设置所需的语言环境,并在退出时使用上述locale.setlocale(locale.LC_TIME, ...) 调用再次恢复旧的语言环境。

【讨论】:

  • 你是完全正确的。 PyQt 搞乱了我的语言环境。因此,我在单独使用 REPL 进行测试时没有收到该错误。
猜你喜欢
  • 2018-05-27
  • 2017-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-26
  • 1970-01-01
  • 2016-06-12
  • 1970-01-01
相关资源
最近更新 更多