Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two date strings in Python

People also ask

Can you compare two date strings?

To compare two date strings:Pass the strings to the Date() constructor to create 2 Date objects. Compare the output from calling the getTime() method on the dates.

How do I compare two days in Python?

Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format . To get the difference between two dates, subtract date2 from date1. A result is a timedelta object.


Use datetime.datetime.strptime:

>>> from datetime import datetime as dt
>>> a = dt.strptime("10/12/13", "%m/%d/%y")
>>> b = dt.strptime("10/15/13", "%m/%d/%y")
>>> a > b
False
>>> a < b
True
>>>

If you like to use the dateutil and its parser:

from dateutil.parser import parse

date1 = parse('10/12/13')
date2 = parse('10/15/13')

print date1 - date2
print date2 > date2

Here's one solution using datetime.datetime.strptime:

>>> date1 = datetime.datetime.strptime('10/12/13', '%m/%d/%y')
>>> date2 = datetime.datetime.strptime('10/15/13', '%m/%d/%y')
>>> date1 < date2
True
>>> date1 > date2
False

Use datetime.datetime.strptime.

from datetime import datetime

a = datetime.strptime('10/12/13', '%m/%d/%y')
b = datetime.strptime('10/15/13', '%m/%d/%y')

print 'a' if a > b else 'b' if b > a else 'tie'

I know this post is 7 years old, but wanted to say that you can compare two date strings without converting them to dates

>>> "10/12/13" > "10/15/13"
False
>>> "10/12/13" < "10/15/13"
True
>>> "10/12/13" == "10/15/13"
False

If there is anything wrong with this approach I would love for someone to tell me.