带有“ +00”时区偏移量格式的Python strptime?

时间:2019-04-11 18:59:48

标签: python date time timezone

如何解析格式为+00的时区偏移量? Python 3或python 2

from datetime import datetime
s = '2019-04-10 21:49:41.607472+00'
# What must I replace <XX> with, to parse +00 as the timezone offset
d = datetime.strptime(s, '%Y-%m-%d %H:%M:%S.%f<XX>')

2 个答案:

答案 0 :(得分:3)

您可以使用dateutil's parse

from dateutil.parser import parse
s = '2019-04-10 21:49:41.607472+00'
parse(s)
  

datetime.datetime(2019,4,10,21,49,41,607472,tzinfo = tzutc())

答案 1 :(得分:3)

strptime使用%z±HHMM[SS[.ffffff]]的格式指定UTC偏移量。由于需要分钟,并且样本输入只有几个小时,因此您可以在解析之前将'00'连接到字符串:

datetime.strptime(s + '00', '%Y-%m-%d %H:%M:%S.%f%z')