1

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!

4
  • You probably want the third-party dateutil library, which does generic parsing of date strings. Commented Feb 6, 2017 at 12:00
  • I presume 5:37:52 is just a time, so do you have some dates and times, and some just times? Commented Feb 6, 2017 at 12:00
  • Yes, i have some "times" which are just minutes and seconds, and some "dates" that are days, hours, minutes and seconds. Commented Feb 6, 2017 at 12:03
  • Thank you Daniel, i will check the dateutil library. Commented Feb 6, 2017 at 12:09

2 Answers 2

3
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

Sign up to request clarification or add additional context in comments.

1 Comment

Yes! Thank you! This works in my case. Also thank you Daniel Roseman for pointing this out!
1

You can use dateutil.parser.parse to parse your time/date strings :

from dateutil.parser import parse
parse("12 05:37:52")
# datetime.datetime(2017, 2, 12, 5, 37, 52)
parse("05:37:52")
# datetime.datetime(2017, 2, 6, 5, 37, 52)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.