我正在尋找Python中兩次的比較。有一次是從計算機上的實時時間,另一次是存儲在格式爲"01:23:00"
的字符串中。Python與其他時間的當前時間比較
import time
ctime = time.strptime("%H:%M:%S") # this always takes system time
time2 = "08:00:00"
if (ctime > time2):
print "foo"
我正在尋找Python中兩次的比較。有一次是從計算機上的實時時間,另一次是存儲在格式爲"01:23:00"
的字符串中。Python與其他時間的當前時間比較
import time
ctime = time.strptime("%H:%M:%S") # this always takes system time
time2 = "08:00:00"
if (ctime > time2):
print "foo"
import datetime
now = datetime.datetime.now()
my_time_string = "01:20:33"
my_datetime = datetime.datetime.strptime(my_time_string, "%H:%M:%S")
# I am supposing that the date must be the same as now
my_datetime = now.replace(hour=my_datetime.time().hour, minute=my_datetime.time().minute, second=my_datetime.time().second, microsecond=0)
if (now > my_datetime):
print "Hello"
編輯:
將上述溶液沒有考慮到閏秒天(23:59:60
)。下面是一個更新的版本,此類案件涉及:
import datetime
import calendar
import time
now = datetime.datetime.now()
my_time_string = "23:59:60" # leap second
my_time_string = now.strftime("%Y-%m-%d") + " " + my_time_string # I am supposing the date must be the same as now
my_time = time.strptime(my_time_string, "%Y-%m-%d %H:%M:%S")
my_datetime = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=calendar.timegm(my_time))
if (now > my_datetime):
print "Foo"
https://docs.python.org/2/library/datetime.html
的datetime
模塊將解析日期,時間,或組合的日期時間值轉換成可以進行比較的對象。
from datetime import datetime
current_time = datetime.strftime(datetime.utcnow(),"%H:%M:%S") #output: 11:12:12
mytime = "10:12:34"
if current_time > mytime:
print "Time has passed."
字符串按字典順序進行比較。我認爲你應該比較日期時間對象。 – felipeptcho
@felipeptcho一般來說,這是一個好得多的事情。它更有保證是正確的,可能更快。在這個具體情況下,按照描述的方式進行操作可能是「安全的」。 – Vatine
@Vatine儘管效率可能很低,但我可以看到您的解決方案不太詳細。那很好!但我很好奇它爲什麼「可能更安全」。 – felipeptcho
請修正你的問題的格式,另外,使它看起來像一個問題(在目前,還沒有一個問號) 。解釋你的代碼,不管它在什麼地方工作。 –
爲什麼你想比較日期時間字符串,這往往會給你錯誤的答案,因爲這些將按照字典順序進行比較。爲什麼不離開或將它們轉換爲日期時間對象,以便您可以直接比較它們。 – AChampion