我正在寻找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")
我正在寻找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")
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")
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."
23:59:60
将无法通过日期时间验证,会抛出异常,我认为这是一个好的方法,因为可以处理异常并向用户呈现消息。另一方面,使用字符串比较将不会验证任何内容,并且会“错误地”将 00:00:00
显示为早于 23:59:60
的时间。 - felipeptcho