How can I check if a date is the same day as datetime.today()?
This condition always evaluates to True
even if it's the same day because it is comparing time.
from datetime import datetime
# ...
if date_num_posts < datetime.today():
How can I check if a date is the same day as datetime.today()
?
Solution 1:
If you want to just compare dates,
yourdatetime.date() < datetime.today().date()
Or, obviously,
yourdatetime.date() == datetime.today().date()
If you want to check that they're the same date.
The documentation is usually helpful. It is also usually the first google result for python thing_i_have_a_question_about
. Unless your question is about a function/module named "snake".
Basically, the datetime
module has three types for storing a point in time:
-
date
for year, month, day of month -
time
for hours, minutes, seconds, microseconds, time zone info -
datetime
combines date and time. It has the methodsdate()
andtime()
to get the correspondingdate
andtime
objects, and there's a handycombine
function to combinedate
andtime
into adatetime
.
Solution 2:
-
If you need to compare only day of month value than you can use the following code:
if yourdate.day == datetime.today().day: # do something
-
If you need to check that the difference between two dates is acceptable then you can use timedelta:
if (datetime.today() - yourdate).days == 0: #do something
-
And if you want to compare date part only than you can simply use:
from datetime import datetime, date if yourdatetime.date() < datetime.today().date() # do something
Note that timedelta has the following format:
datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
So you are able to check diff in days, seconds, msec, minutes and so on depending on what you really need:
from datetime import datetime
if (datetime.today() - yourdate).days == 0:
#do something
In your case when you need to check that two dates are exactly the same you can use timedelta(0):
from datetime import datetime, timedelta
if (datetime.today() - yourdate) == timedelta(0):
#do something
Solution 3:
You can set the hours, minutes, seconds and microseconds to whatever you like
datetime.datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)
but trutheality's answer is probably best when they are all to be zero and you can just compare the .date()
s of the times
Maybe it is faster though if you have to compare hundreds of datetimes because you only need to do the replace()
once vs hundreds of calls to date()