蟒蛇。将字符串转换为datetime会引发ValueError

时间:2016-02-01 17:51:42

标签: python python-3.x datetime

我有字符串:

import datetime
time = "2016-02-01 19:14:54+02:00"

并尝试将其转换为datetime obj:

result = datetime.datetime.strptime(time, "%Y-%m-%d %H:%M:%S%z")

抛出异常:

ValueError: time data '2016-02-01 19:14:54+02:00' does not match format '%Y-%m-%d %H:%M:%S%z'

你能帮我解决这里有什么问题吗?

3 个答案:

答案 0 :(得分:5)

根据py %z specification,时区偏移:在小时和分钟之间不应有strptime

>>>> datetime.datetime.strptime("2016-02-01 19:14:54+02:00", "%Y-%m-%d %H:%M:%S%z")
ValueError: time data '2016-02-01 19:14:54+02:00' does not match format '%Y-%m-%d %H:%M:%S%z'

>>> datetime.datetime.strptime("2016-02-01 19:14:54+0200", "%Y-%m-%d %H:%M:%S%z")
datetime.datetime(2016, 2, 1, 19, 14, 54, tzinfo=datetime.timezone(datetime.timedelta(0, 7200)))

答案 1 :(得分:2)

您的日期看起来像iso8601格式,您可以使用dateutil

time = "2016-02-01 19:14:54+02:00"
from dateutil import parser

dte = parser.parse(time)

输出:

In [7]: from dateutil import parser
In [8]: time = "2016-02-01 19:14:54+02:00"
In [9]: dte = parser.parse(time)   
In [10]: dte
Out[10]: datetime.datetime(2016, 2, 1, 19, 14, 54, tzinfo=tzoffset(None, 7200))

In [11]: dte.utcoffset()
Out[11]: datetime.timedelta(0, 7200)

答案 2 :(得分:2)

strptime不会解析时区中:的{​​{3}}格式化日期时间字符串(感谢@håken-lid),这就是您"2016-02-01 19:14:54+02:00"的示例的。

您可以使用:

iso8601图书馆建议:

from dateutil import parser
time = "2016-02-01 19:14:54+02:00"
dte = parser.parse(time)   
dte
datetime.datetime(2016, 2, 1, 19, 14, 54, tzinfo=tzoffset(None, 7200))

dte.utcoffset()
datetime.timedelta(0, 7200)

dateutil

import xml.utils.iso8601
xml.utils.iso8601.parse("2004-04-09T21:39:00-08:00")

xml.utils

import iso8601
iso8601.parse_date("2007-01-25T12:00:00Z")
datetime.datetime(2007, 1, 25, 12, 0, tzinfo=<iso8601.Utc>)