我在Python中寻找两次比较。一次是来自计算机的实时,另一次是存储在格式为"01:23:00"
的字符串中。
import time
ctime = time.strptime("%H:%M:%S") # this always takes system time
time2 = "08:00:00"
if (ctime > time2):
print "foo"
答案 0 :(得分:5)
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"
答案 1 :(得分:0)
https://docs.python.org/2/library/datetime.html
datetime
模块会将日期,时间或组合日期时间值解析为可比较的对象。
答案 2 :(得分:0)
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."