0

I have 2 dates defined as a strings. If I would know the original date format, I would compare it like this:

import time
date1 = "1/1/2013 12:00:00 AM" # formatted like "%m/%d/%Y %H:%M:%S %p"
date2 = "1/1/2016"             # formatted like "%m/%d/%Y"
format1 = "%m/%d/%Y %H:%M:%S %p"
format2 = "%m/%d/%Y"
if time.strptime(date1, format1) > time.strptime(date2, format2):
   pass

How can I compare it if I do not know the date format?

2
  • The best you'll be able to do is trying various formats and seeing if one succeeds. You might be able to speed that process up by examining the string beforehand to select which candidate formats to try first (and not bother with those that couldn't possibly work). Commented May 31, 2017 at 14:54
  • Thanks I did write my own solution of this problem with try - except block. Commented Jun 1, 2017 at 14:47

2 Answers 2

2

How can I compare it if I do not know the date format?

You can't. Every comparison assumes that you know what you are comparing.

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

Comments

1

You can try to parse it with dateutil.parser.parse. This method parse a string in one of the supported formats. And then compare it.

datautil is a third-party module.

1 Comment

This is exactly what I'm searching for!

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.