geirmash geirmash - 4 years ago 108
Python Question

Comparing datetimes of different formats in python

I am trying to compare two dates in Python of different formats. Meaning, the "dates" can be of format "%d %H:%M:%S", "%H:%M:%S" or even "%M:%S".
Initially i am working with datetimes of format "%a %b %d %H:%M:%S +0000 %Y".
When i am trying to do as explained above i get the error:

ValueError: time data '5:37:52' does not match format '%a %b %d %H:%M:%S +0000 %Y'


Which indeed is a logical error to get.

But are there any method or built in function in python that can handle different datetime formats? Or even a workaround?

I am using Python 2.7.12.

Thank you in advance for any help!

Answer Source
from dateutil.parser import parse
print( parse( "5:37:52" ) )
datetime.datetime(2017, 2, 6, 5, 37, 52)

As Daniel pointed out the dateutil library will parse dates in various formats, so you just need to pass all your date strings through it in order to get the datetime objects

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download