2011-12-16 70 views
1

我想比較兩次,如果新的時間超過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 
+0

差異是datetime.timedelta對象,它有.totalseconds()方法或.seconds財產 – yosukesabai 2011-12-16 15:00:43

+0

感謝yosukesabai – krisdigitx 2011-12-16 15:05:43

回答

3

減去2種datetime情況下返回timedelta具有total_seconds方法:

contant = 2 * 60 
diff = late-now 
if diff.total_seconds() <= constant: 
2

這只是一個問題的更新,因爲從sje397答案是完美的。

使用格式字符串這樣對整個時間匹配字符串:

nnow = datetime.strptime(now, '%Y-%m-%d %H:%M:%S.%f') 

的%F微秒後點相匹配。這是自Python 2.6以來的新增功能。

1

你可以自己比較datetime對象:

from datetime import datetime, timedelta 

ts = datetime.strptime("2011-12-16 16:14:50.838638Z", '%Y-%m-%d %H:%M:%S.%fZ') 
ts += timedelta(minutes=2) # add 2 minutes 

if datetime.utcnow() < ts: 
    print("time is less") 
else: 
    print("time is more or equal")