简体   繁体   中英

How to check if a date has Passed in Python (Simply)

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.

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
from datetime import datetime
present = datetime.now()
print datetime(2015,04,30) < present #should return true

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

Just compare them?

>>> t1 = datetime.datetime.now()
>>> t2 = datetime.datetime.now()
>>> t1>t2
False
>>> t1<t2
True

You can create a simple function which does this:

def has_expired(date):
    import datetime

    return date < datetime.datetime.now()

Two line code here

from datetime import datetime
print datetime(2015,04,30) < datetime.strptime(inputdate, "%d/%m/%Y").date()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM