0

I need to compare two dates given below:

my_date = 'Mar 15 00:00:00 2019'
date_to_check = "Sep 17 04:00:05 2018"

if my_date<=date_to_check:
     print(True)

It should not print anything. But it is printing 'True'. I figured out the problem- It is comparing only Mar 15 to Sep 17, not taking year into consideration. And I cannot change date format to some other because I need to compare the dates in the text file.

Any comments on this.

3
  • In the question, I see a code snippet comparing strings not dates, and date_to_check is lexicographically larger than my_date. See: stackoverflow.com/questions/4806911/… Commented Mar 29, 2019 at 14:18
  • 2
    Possible duplicate of Comparing two date strings in Python Commented Mar 29, 2019 at 14:18
  • @vahdet, yeah I saw that date_to_check is lexicographically larger than my_date,. Is there any way to compare these two date strings? Commented Mar 29, 2019 at 14:40

1 Answer 1

0
from datetime import datetime

my_date = 'Mar 15 00:00:00 2019'
date_to_check = "Sep 17 04:00:05 2018"

my_date_object = datetime.strptime(my_date, '%b %d %H:%M:%S %Y')
date_to_check_object = datetime.strptime(date_to_check, '%b %d %H:%M:%S %Y')

if my_date_object <= date_to_check_object:
    print(True)
Sign up to request clarification or add additional context in comments.

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.