Short date format still has time

128 views Asked by At

I am having date troubles with a python script I am writing. Why is this false? I am not understanding why 00:00:00 is still present even though I have explicitly requested only the day, month, year?

date1 = datetime.strptime('22 Dec 2016', '%d %b %Y') <-- 2016-12-12 00:00:00
date2 = datetime.today().date()
print(date1==date2)  # False
2

There are 2 answers

1
Martijn Pieters On BEST ANSWER

You are comparing a datetime object and a date object; datetime.strptime() always produces a datetime instance; even though the time is set to midnight, that's still a date and time combination.

To compare only dates, you need to do so explicitly.

Either:

date1.date() == date2  # extract the date, compare to the other date

or

from datetime import time

# compare the datetime to another datetime with midnight
date1 == datetime.combine(date2, time.min)
0
Rakesh Kumar On

First thing you are checking it in wrong direction. Here comparison takes place between datetime and date. Compare date with date then it provide TRUE. 00:00:00 Still present as datetime always have time associated with it, so here it is keeping 00:00:00 as no time provided.

date1 = datetime.strptime('22 Dec 2016', '%d %b %Y') <-- 2016-12-12 00:00:00
date2 = datetime.today().date()
print(date1==date2)
False



print(date1.date()==date2)
True