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?
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With