DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 968,547 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
antlossway
antlossway

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)

Find what you were looking for? Sign up so you can:

🌚 Enable dark mode
πŸ”  Change your default font
πŸ“š Adjust your experience level to see more relevant content