Fix Python – How can I check if a date is the same day as datetime.today()?

Question

Asked By – madprops

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

Now we will see solution for issue: How can I check if a date is the same day as datetime.today()?


Answer

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.

This question is answered By – trutheality

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0