130

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()?

MarredCheese
  • 17,541
  • 8
  • 92
  • 91
madprops
  • 3,909
  • 5
  • 34
  • 42

5 Answers5

237

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 methods date() and time() to get the corresponding date and time objects, and there's a handy combine function to combine date and time into a datetime.
trutheality
  • 23,114
  • 6
  • 54
  • 68
  • 11
    "It is also usually the first google result for python thing_i_have_a_question_about" And unless somebody made SO entry on this topic, like it happened here :) – reducing activity Sep 07 '18 at 11:48
  • 1
    You can also write `datetime.date.today()` for today's date that is similar to `datetime.today().date()`. – Timo Mar 24 '22 at 07:15
50
  • 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
Artsiom Rudzenka
  • 27,895
  • 4
  • 34
  • 52
  • 1
    `.day` is the day-of-the-month. So August 12 is "equal" to December 12 using your first snippet of code. That's probably not the behavior the OP wants. – trutheality Jun 20 '11 at 06:29
  • @trutheality - yep, i started to write my answer before question has been edited, so i was not able to understand what he exactly need, that is why i provide several options for this – Artsiom Rudzenka Jun 20 '11 at 06:32
  • 1
    Quick note: datetime objects have an attribute called 'day' (no 's') and timedelta objects have an attribute called 'days' (with an 's') in case people find themselves befuddled with why their syntax isn't working. – user1847 Sep 25 '17 at 23:14
4

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()

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • I'd vote for this if it didn't involve mutation. You can however adapt this method by creating a clone of the datetime objects you're comparing, then modify them by removing fields with sub-day resolution, then compare the copies. – ninjagecko Jun 20 '11 at 06:20
  • 1
    @ninja, it doesn't mutate. replace() returns a new datetime object, like str.replace() does – John La Rooy Jun 20 '11 at 06:27
2
all(getattr(someTime,x)==getattr(today(),x) for x in ['year','month','day'])

One should compare using .date(), but I leave this method as an example in case one wanted to, for example, compare things by month or by minute, etc.

ninjagecko
  • 88,546
  • 24
  • 137
  • 145
2

Another alternative is to convert the date in strings and compare them.

from datetime import datetime

today= datetime.today()

if today.strftime('%Y-%m-%d') == other_datetime.strftime('%Y-%m-%d'):
    print("same day as today: {0}".format(today.strftime('%Y-%m-%d')))
Papouche Guinslyzinho
  • 5,277
  • 14
  • 58
  • 101
  • down-voted for not comparing data but datas shapes. There is a way to compare data, see trutheality's answer – mgueydan Jan 27 '22 at 13:07