Federico Sciarretta
Federico Sciarretta

Reputation: 372

Comparing 2 dates with python

I need to compare 2 dates with a IF, but for some strange (:P) reason, I can't do it. My code

date1 = strftime("%Y-%m-%d")
d2 = os.path.getmtime('/tmp/file')
date2 = datetime.date.fromtimestamp(d2)
if date1 == date2 :
    print 'same date'
else:
    print 'different date'

I don't know why, show with a print the same date, but, with this IF shows 'different date' Maybe is a newbie question, sorry !

Thank you !

Upvotes: 1

Views: 978

Answers (2)

Niklas B.
Niklas B.

Reputation: 95328

  • time.strftime returns an object of type str (a "string")
  • datetime.date.fromtimestamp returns an object of type datetime.date

So date1 and date2 will be objects of different types. Comparing to objects of different types will always yield False (this is an aspect of strong typing)

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799170

date1 is a string, and date2 is a datetime.date. Perhaps you meant date1 = datetime.date.today().

Upvotes: 5

Related Questions