使用Python中的DateTime模块比较时间



我必须找到格式 datetime.datetime.now().replace(microsecond=0)的某个时间段是否大于5分钟。我怎样才能做到这一点?这是我的代码:

ttime = datetime.now().replace(microsecond=0)
print "Current Time:- "+str(ttime)
a = raw_input("Press y and Enter")
if a=="y":
    print "OK!"
    ntime = datetime.now().replace(microsecond=0)
    difference = ntime-ttime
    if difference> #I don't know what to put!:
        print "Difference is greater than 5 min"
    else:
        print "Difference is not greater than 5 min"

您可以使用difference = timedelta(minutes=5)

>>> from datetime import datetime, timedelta
>>> ttime = datetime.now().replace(microsecond=0)
>>> ntime = datetime.now().replace(microsecond=0)
>>> ntime - ttime > timedelta(minutes=5)
True

timedelta用5分钟初始化的对象:

>>> timedelta(minutes=5)
datetime.timedelta(0, 300)

要获取更多信息,请阅读有关timedelta对象的文档。

import datetime
ttime = datetime.datetime.now().replace(microsecond=0)
print "Current Time:- "+str(ttime)
a = raw_input("Press y and Enter")
if a=="y":
    print "OK!"
    ntime = datetime.datetime.now().replace(microsecond=0)
    if ttime < ntime - datetime.timedelta(minutes=5):
        print "Difference is greater than 5 min"
    else:
        print "Difference is not greater than 5 min"

相关内容

  • 没有找到相关文章

最新更新