我想比較兩次,如果新的時間超過2分鐘,然後if語句將打印輸出,我可以得到datetime.datetime.now()的輸出,但怎麼做我檢查舊時間是否少於2分鐘?蟒蛇減去時間並運行循環
#!/usr/bin/env python
import datetime
from time import sleep
now = datetime.datetime.now()
sleep(2)
late = datetime.datetime.now()
constant = 2
diff = late-now
if diff <= constant:
print "True time is less than 2min"
else:
print "Time exceeds 2 mins"
有什麼想法?
更新:
我現在保存舊日期在文件字符串,然後從當前時間減去它,舊的日期存儲格式
2011-12-16 16:14: 50.800856
所以當我做
now = "2011-12-16 16:14:50.838638"
sleep(2)
nnow = datetime.strptime(now, '%Y-%m-%d %H:%M:%S')
late = datetime.now()
diff = late-nnow
它給了我這個錯誤
ValueError: unconverted data remains: .838638
差異是datetime.timedelta對象,它有.totalseconds()方法或.seconds財產 – yosukesabai 2011-12-16 15:00:43
感謝yosukesabai – krisdigitx 2011-12-16 15:05:43