Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to datetime with milliseconds and timezone - Python

Tags:

python

I have the following python snippet:

from datetime import datetime

timestamp = '05/Jan/2015:17:47:59:000-0800'
datetime_object = datetime.strptime(timestamp, '%d/%m/%y:%H:%M:%S:%f-%Z')
print datetime_object

However when I execute the code, I'm getting the following error:

ValueError: time data '05/Jan/2015:17:47:59:000-0800' does not match format '%d/%m/%y:%H:%M:%S:%f-%Z'

what's wrong with my matching expression?

like image 484
cybertextron Avatar asked Oct 30 '25 07:10

cybertextron


1 Answers

EDIT 2: According to this post, strptime doesn't support %z (despite what the documentation suggests). To get around this, you can just ignore the timezone adjustment?:

from datetime import datetime

timestamp = '05/Jan/2015:17:47:59:000-0800'
# only take the first 24 characters of `timestamp` by using [:24]
dt_object = datetime.strptime(timestamp[:24], '%d/%b/%Y:%H:%M:%S:%f')
print(dt_object)

Gives the following output:

$ python date.py
2015-01-05 17:47:59

EDIT: Your datetime.strptime argument should be '%d/%b/%Y:%H:%M:%S:%f-%z'

With strptime(), %y refers to

Year without century as a zero-padded decimal number

I.e. 01, 99, etc.

If you want to use the full 4-digit year, you need to use %Y

Similarly, if you want to use the 3-letter month, you need to use %b, not %m

I haven't looked at the rest of the string, but there are possibly more mismatches. You can find out how each section can be defined in the table at https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

like image 192
rst-2cv Avatar answered Nov 01 '25 20:11

rst-2cv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!