DEV Community

Quinn
Quinn

Posted on

1 1

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay