The Python Oracle

How to compare two dates?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Dream Voyager Looping

--

Chapters
00:00 How To Compare Two Dates?
00:22 Accepted Answer Score 662
00:37 Answer 2 Score 51
00:51 Answer 3 Score 114
01:23 Answer 4 Score 5
01:45 Thank you

--

Full question
https://stackoverflow.com/questions/8142...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #datetime

#avk47



ACCEPTED ANSWER

Score 662


Use the datetime method and the operator < and its kin.

>>> from datetime import datetime, timedelta
>>> past = datetime.now() - timedelta(days=1)
>>> present = datetime.now()
>>> past < present
True
>>> datetime(3000, 1, 1) < present
False
>>> present - datetime(2000, 4, 4)
datetime.timedelta(4242, 75703, 762105)



ANSWER 2

Score 114


Use time

Let's say you have the initial dates as strings like these:

date1 = "31/12/2015"
date2 = "01/01/2016"

You can do the following:

newdate1 = time.strptime(date1, "%d/%m/%Y")
newdate2 = time.strptime(date2, "%d/%m/%Y")

to convert them to python's date format. Then, the comparison is obvious:

  • newdate1 > newdate2 will return False
  • newdate1 < newdate2 will return True



ANSWER 3

Score 51


datetime.date(2011, 1, 1) < datetime.date(2011, 1, 2) will return True.

datetime.date(2011, 1, 1) - datetime.date(2011, 1, 2) will return datetime.timedelta(-1).

datetime.date(2011, 1, 1) - datetime.date(2011, 1, 2) will return datetime.timedelta(1).

see the docs.




ANSWER 4

Score 5


Other answers using datetime and comparisons also work for time only, without a date.

For example, to check if right now it is more or less than 8:00 a.m., we can use:

import datetime

eight_am = datetime.time( 8,0,0 ) # Time, without a date

And later compare with:

datetime.datetime.now().time() > eight_am  

which will return True