DEV Community

Quinn
Quinn

Posted on

python: compare dates

An easy way to compare dates is to use comparison operators like <, >, <=, >=, != etc.

Case study:

I have a configuration file (text) including effective_date, and I need to compare if today is later than effective_date, if yes, then I need to perform some checking;
otherwise nothing need to be done.

""" extract effective_date from configuration file 
    line is obtained from readline() after open the 
    configuration file
"""
(param1,param2,effective_date) = line.strip().split(',')

"" use list comprehension to extract year,month,day
 to build a datetime.date type, """
year,month,day = [int(x) for x in effective_date.split('-')]
date_obj = datetime.date(year,month,day) #datetime.date type

today = datetime.date.today()

if today >= date_obj:
    """ do something here """
Enter fullscreen mode Exit fullscreen mode

datetime.datetime type can also be compared in the same way, just make sure the compared objects have the same type.

Top comments (0)