16

I have looked around to see if I can find a simple method in Python to find out if a date has passed.

For example:- If the date is 01/05/2015, and the date; 30/04/2015 was in-putted into Python, it would return True, to say the date has passed.

This needs to be as simple and efficient as possible.

Thanks for any help.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
DibDibsTH13TEEN
  • 171
  • 1
  • 1
  • 9
  • 3
    You say you have looked around, did you find any solutions? Why were they not acceptable? –  Apr 30 '15 at 18:40
  • The `time` and `datetime` modules can be used to convert strings into floats (representing seconds since the epoch) or datetime objects and to get the current time. A simple compare does the rest. – tdelaney Apr 30 '15 at 18:43
  • 2
    possible duplicate of [Compare dates in Python with datetime](http://stackoverflow.com/questions/17768928/compare-dates-in-python-with-datetime) – Gus E Apr 30 '15 at 18:44
  • possible duplicate of [How to compare two dates?](http://stackoverflow.com/questions/8142364/how-to-compare-two-dates) – clesiemo3 Apr 30 '15 at 19:19

4 Answers4

14

you may use datetime, first parse String to date, then you can compare

import datetime
d1 = datetime.datetime.strptime('05/01/2015', "%d/%m/%Y").date()
d2 = datetime.datetime.strptime('30/04/2015', "%d/%m/%Y").date()
d2>d1
Jose Ricardo Bustos M.
  • 8,016
  • 6
  • 40
  • 62
13
from datetime import datetime
present = datetime.now()
print datetime(2015, 4, 30) < present #should return true

Sourced some material from this question/answer: How to compare two dates?

Tom Susel
  • 3,397
  • 1
  • 24
  • 25
clesiemo3
  • 1,099
  • 6
  • 17
7

Just compare them?

>>> t1 = datetime.datetime.now()
>>> t2 = datetime.datetime.now()
>>> t1>t2
False
>>> t1<t2
True
toucan
  • 1,465
  • 1
  • 17
  • 31
2

You can create a simple function which does this:

def has_expired(date):
    import datetime

    return date < datetime.datetime.now()
V. Sambor
  • 12,361
  • 6
  • 46
  • 65