简体   繁体   English

如何检查日期是否已通过Python传递(简单)

[英]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. 我环顾四周,看看我是否可以在Python中找到一个简单的方法来查明日期是否已经过去。

For example:- If the date is 01/05/2015 , and the date; 例如: - 如果日期是2015年5 01/05/2015日,那么日期; 30/04/2015 was in-putted into Python, it would return True, to say the date has passed. 30/04/2015被输入Python,它会返回True,说日期已经过去了。

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 你可以使用datetime,首先解析String到日期,然后你可以比较

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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