Arpit
Arpit

Reputation: 6260

Python - Time data not match format

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?

Upvotes: 1

Views: 8615

Answers (4)

neverwalkaloner
neverwalkaloner

Reputation: 47354

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)

Upvotes: 0

Anonymous
Anonymous

Reputation: 12090

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)

Upvotes: 0

Burhan Khalid
Burhan Khalid

Reputation: 174624

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'

Upvotes: 4

Oxymoron88
Oxymoron88

Reputation: 495

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

Upvotes: 0

Related Questions