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.

user15051990
  • 1,835
  • 2
  • 28
  • 42
  • In the question, I see a code snippet comparing strings *not dates*, and `date_to_check` is lexicographically larger than `my_date`. See: https://stackoverflow.com/questions/4806911/string-comparison-technique-used-by-python – vahdet Mar 29 '19 at 14:18
  • 2
    Possible duplicate of [Comparing two date strings in Python](https://stackoverflow.com/questions/20365854/comparing-two-date-strings-in-python) – glibdud Mar 29 '19 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? – user15051990 Mar 29 '19 at 14:40

1 Answers1

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)
ncica
  • 7,015
  • 1
  • 15
  • 37