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.

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

Neon image

Set up a Neon project in seconds and connect from a Python application

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s day—drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay