我输入以下字符串:
input = "20170620015620.222+0000"
要将其转换为datetime
,我可以使用以下内容:
utc_format_regex = re.compile('(?P<year>\d{4})'
'(?P<month>\d{2})'
'(?P<day>\d{2})'
'(?P<hour>\d{2})'
'(?P<minute>\d{2})'
'(?P<second>\d{2})'
'\.'
'(?P<milisecond>\d{3})'
'(?P<tz>\+\d{4})')
year, month, day, hour, minute, second, milisecond, tz = utc_format_regex.match(value).groups()
将此解析为日期时间似乎很简单,除了param tzinfo(我不知道如何正确使用它)。该代码因为这样的错误而无法工作:
TypeError: tzinfo argument must be None or of a tzinfo subclass, not type 'unicode'
datetime(year=int(year), month=int(month), day=int(day), hour=int(hour), minute=int(minute), second=int(second),
microsecond=int(milisecond) * 1000, tzinfo=tz)
答案 0 :(得分:1)
只需使用strptime
:
import datetime
parsed = datetime.datetime.strptime(input, '%Y%m%d%H%M%S.%f%z')