【发布时间】:2017-03-04 19:49:20
【问题描述】:
我想将字符串转换为日期时间。
字符串是:
date_created = "2016-10-22T16:27:54+0000"
我正在尝试将其转换为:
datetime.strptime(date_created, '%y-%m-%dT%H:%M:%S+0000')
但格式不匹配。
那么,正确的格式是什么?
【问题讨论】:
我想将字符串转换为日期时间。
字符串是:
date_created = "2016-10-22T16:27:54+0000"
我正在尝试将其转换为:
datetime.strptime(date_created, '%y-%m-%dT%H:%M:%S+0000')
但格式不匹配。
那么,正确的格式是什么?
【问题讨论】:
%y 匹配具有两位数的年份,但您的输入使用 4 位数字。请改用%Y:
>>> from datetime import datetime
>>> date_created = "2016-10-22T16:27:54+0000"
>>> datetime.strptime(date_created, '%Y-%m-%dT%H:%M:%S+0000')
datetime.datetime(2016, 10, 22, 16, 27, 54)
来自strftime() and strptime() Behavior section:
%y
以零填充十进制数表示的没有世纪的年份。00, 01, ..., 99
%Y年份,世纪为十进制数。0001, 0002, ..., 2013, 2014, ..., 9998, 9999
【讨论】: