Python - Time data not match format

岁酱吖の 提交于 2019-12-02 09:03:08

问题


I have string time in the following format

2016-12-10T13:54:15.294

I am using the following method to format the time:

time.strptime(ts, '%b %d %H:%M:%S %Y')

Which throws an error:
time data did not match format: data=2016-12-10T13:54:15.294 fmt=%a %b %d %H:%M:%S %Y

Any ideas where I am going wrong?


回答1:


You need to first parse the string as its formatted, then print it out the way you want.

>>> import datetime
>>> ts = "2016-12-10T13:54:15.294"
>>> parsed = datetime.datetime.strptime(ts, '%Y-%m-%dT%H:%M:%S.%f')
>>> parsed
datetime.datetime(2016, 12, 10, 13, 54, 15, 294000)
>>> parsed.strftime('%b %d %H:%M:%S %Y')
'Dec 10 13:54:15 2016'



回答2:


I think your date format is incorrectly specified in string. This should work:

import datetime
a = '2016-12-10T13:54:15.294'
b= datetime.datetime.strptime(a,'%Y-%m-%dT%H:%M:%S.%f')
print b



回答3:


The error is not wrong, the format string is not even close to the string you're trying to parse.

You have {year}-{month}-{day}T{hour}:{minute}:{second}.{milliseconds} but trying to parse it with {weekday name} {month name} {day} {hour}:{minute}:{second} {year}. Did you copy this from somewhere?

According to the documentation, your format string should look more like %Y-%m-%dT%H:%M:%S.%f.

>>> time.strptime('2016-12-10T13:54:15.294', '%Y-%m-%dT%H:%M:%S.%f')
time.struct_time(tm_year=2016, tm_mon=12, tm_mday=10, tm_hour=13, tm_min=54, tm_sec=15, tm_wday=5, tm_yday=345, tm_isdst=-1)



回答4:


Your format string is not correct.

You can check format string just using strftime method of date object. For example:

d = datetime.datetime.now()
print(d.strftime('%Y-%d-%mT%H:%M:%S'))

Output:

Dec 16 11:02:46 2016

But you have string in following format 2016-12-10T13:54:15.294, so you just need to change format string:

print(time.strptime(ts, '%Y-%d-%mT%H:%M:%S.%f'))

output:

time.struct_time(tm_year=2016, tm_mon=10, tm_mday=12, tm_hour=13, tm_min=54, tm_sec=15, tm_wday=2, tm_yday=286, tm_isdst=-1)


来源:https://stackoverflow.com/questions/41177992/python-time-data-not-match-format

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!