如何用冒号解析时区

2024-04-27 04:06:42 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法用datetime.strptime解析“+00:00”格式的时区?例如:

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> datetime.strptime("12:34:56+0000", "%X%z")
datetime.datetime(1900, 1, 1, 12, 34, 56, tzinfo=datetime.timezone.utc)
>>> datetime.strptime("12:34:56+00:00", "%X%z")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python34\lib\_strptime.py", line 500, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "C:\Python34\lib\_strptime.py", line 337, in _strptime
    (data_string, format))
ValueError: time data '12:34:56+00:00' does not match format '%X%z'

有什么想法吗?


Tags: inpyformatdatadatetimestringlib格式
3条回答

改编自被拒绝的编辑:

Python>;=3.7:

from datetime import datetime
d = "2019-12-25T23:59:59+00:00"
print(datetime.strptime(d, "%Y-%m-%dT%H:%M:%S%z"))

Changed in version 3.7: When the %z directive is provided to the strptime() >method, the UTC offsets can have a colon as a separator between hours, minutes >and seconds. For example, '+01:00:00' will be parsed as an offset of one hour. In >addition, providing 'Z' is identical to '+00:00'.

https://docs.python.org/3.7/library/datetime.html

Python<;=3.6

没有内置方式,但最好的解决方案是:

from datetime import datetime
d = "2019-12-25T23:59:59+00:00"
if ":" == d[-3]:
    d = d[:-3]+d[-2:]
print(datetime.strptime(d, "%Y-%m-%dT%H:%M:%S%z"))

说明: https://bugs.python.org/issue15873https://bugs.python.org/msg169952

另一种解决方案是使用dateutil库:

from dateutil import parser

mystr = '2015-04-30T23:59:59+00:00'

x = parser.parse(mystr)

# 2015-04-30 23:59:59+00:00

目前,还没有治愈的方法,这里是和解释:https://bugs.python.org/issue15873更准确地说,这里是:https://bugs.python.org/msg169952。 但你可以通过这种方式来解决这个问题:

from datetime import datetime
d = "2015-04-30T23:59:59+00:00"
if ":" == d[-3:-2]:
    d = d[:-3]+d[-2:]
print(datetime.strptime(d, "%Y-%m-%dT%H:%M:%S%z"))

相关问题 更多 >