Dgstah Dgstah - 1 year ago 85
Python Question

How do I convert a date string containing 7 digits in milliseconds into a date in Python

When the milliseonds have 6 digits, %f works, but it throws an error if there are more than 6 digits. I have a temporary solution by hardcoding a 0 for the 7th digit, but is there a better way to do? Currently the below works

print (datetime.datetime.strptime(('2014-11-19 00:00:00.0000000').strip(), '%Y-%m-%d %H:%M:%S.0%f')).date()

Answer Source

According to the documentation of datetime.strptime() https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior, technical note (4), %f accepts only 1 - 6 chars:

%f is an extension to the set of format characters in the C standard (but implemented separately in datetime objects, and therefore always available). When used with the strptime() method, the %f directive accepts from one to six digits and zero pads on the right.

I do NOT believe you have solved the problem correctly. You should not prefix the string with zero, but instead drop everything past 6 (which is less significant to contributing to time).

Something like this:

s='2014-11-19 00:00:00.0000000'
print (datetime.datetime.strptime((s[:26]).strip(), '%Y-%m-%d  %H:%M:%S.%f')).date()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download