我正在寻找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