Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datetime from string doesn't match

I am trying to match a specific datetime format from a string but I am receiving a ValueError and I am not sure why. I am using the following format:

t = datetime.datetime.strptime(t,"%b %d, %Y %H:%M:%S.%f Eastern Standard Time")

which is an attempt to match the following string:

Nov 19, 2017 20:09:14.071360000 Eastern Standard Time

Can anyone see why these do not match?

like image 691
Alex Avatar asked Mar 10 '26 13:03

Alex


2 Answers

From the docs we can see that %f expects:

Microsecond as a decimal number, zero-padded on the left.

The problem with your string is that you have a number that's zero-padded on the right.

Here is one way to fix your issue:

new_t = t.partition(" Eastern Standard Time")[0].rstrip('0') + ' Eastern Standard Time'
print(new_t)
#Nov 19, 2017 20:09:14.07136 Eastern Standard Time

t2 = datetime.datetime.strptime(new_t,"%b %d, %Y %H:%M:%S.%f Eastern Standard Time")
print(t2)
#datetime.datetime(2017, 11, 19, 20, 9, 14, 71360)
like image 182
pault Avatar answered Mar 12 '26 02:03

pault


As noted by pault and the documentation, the issue is that the %f directive is essentially limited to 6 decimal places for your microseconds. While their solution works fine for your string, you might have an issue if your string is something like

'Nov 19, 2017 20:09:14.071360123 Eastern Standard Time'

Because calling rstrip('0') in that case would not cut the microseconds to the proper length. You could otherwise do the same with regex:

import re
import datetime

date_string = 'Nov 19, 2017 20:09:14.071360123 Eastern Standard Time'
# use a regex to strip the microseconds to 6 decimal places:
new_date_string = ''.join(re.findall(r'(.*\.\d{6})\d+(.*)', date_string)[0])
print(new_date_string)
#'Nov 19, 2017 20:09:14.071360 Eastern Standard Time'

t = datetime.datetime.strptime(new_date_string,"%b %d, %Y %H:%M:%S.%f Eastern Standard Time")    
print(t)
#datetime.datetime(2017, 11, 19, 20, 9, 14, 71360)
like image 35
sacuL Avatar answered Mar 12 '26 04:03

sacuL