Python test datetime object if it is in the past present or future

Question:

in python, if I have a date string in the following format yyyy-mm-dd, I would like to write a function to check if the date is in the past, present or future. However, I am having some trouble with this. I have written the following code…

from datetime import datetime

def check_date(date_string):
    this_date = datetime.strptime(date_string, '%Y-%m-%d')
    now = datetime.today()
    if this_date < now:
        print("the date is in the past")
    elif this_date > now:
        print("the day is in the future")
    else:
        print("the day is today")

however, when I tested this, it gives me…

>>check_date('2022-08-08')
the date is in the past
>>check_date('2022-10-10')
the day is in the future
>>check_date('2022-09-22') #this is todays date
the date is in the past

I’m not sure why it is giving this unexpected behaviour.
thanks

Asked By: user19245296

||

Answers:

datetime.datetime.today() includes both date and time, as a quick debug print would have shown. Use this:

import datetime

def check_date(date_string):
    this_date = datetime.datetime.strptime(date_string, '%Y-%m-%d')
    now = datetime.date.today()
...
Answered By: Tim Roberts

I believe the problem is where you get the today’s date. datetime.today() create an instance which includes hours, minutes, seconds in addition to year, month, day. However, you are trying to compare them with date only (i.e., year, month, day format.

If you consider date.today() instead of datetime.today(), you should be good to go.

Answered By: Mohammad Tehrani

Try this!

from datetime import datetime

def check_date(date_string):
    this_date = datetime.strptime(date_string, '%Y-%m-%d').date()
    now = datetime.today().date()
    print(now, this_date)
    if this_date < now:
        print("the date is in the past")
    elif this_date > now:
        print("the day is in the future")
    else:
        print("the day is today")
Answered By: Shakya Dissanayake
from datetime import datetime
year = 2022
month = 9
day = 22
Date_to_check = datetime.date(datetime(year,month,day))
current_day = datetime.date(datetime.now())

if Date_to_check == current_day:
    print("it is present")
elif Date_to_check > current_day:
    print("it is future")
else:
    print("it is past")

please review this code and you’ll get some idea how it is working.

Answered By: cpu_overclocked
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.