Python当前时间与其他时间的比较

5

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

3
请修正你的问题格式,同时让它看起来像一个问题(目前没有一个问号)。解释你的代码以及其中不起作用的部分。 - barak manos
2
为什么要尝试比较日期时间字符串呢?这通常会导致错误的结果,因为它们将按字典顺序进行比较。为什么不将它们转换为日期时间对象,以便您可以直接进行比较或者保持原样呢? - AChampion
3个回答

11
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")

0

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."

字符串按字典顺序进行比较。我认为你应该比较日期时间对象。 - felipeptcho
@felipeptcho 一般来说,这是更好的做法。它更有保证是正确的,而且可能更快。在这种特定情况下,按照所描述的方式做可能是“安全”的。 - Vatine
@Vatine 我可以看到你的解决方案虽然可能效率较低,但更为简洁。这很好!但我很好奇它为什么“可能更安全”。 - felipeptcho
@felipeptcho 不是“可能更安全”,而是“可能是安全的”。如果您正在使用24小时时间戳(其中%H作为格式),则在“00:00:00”和“23:59:60”之间没有时间,时间比较和字符串比较应该一致。为什么不在比较之前将时间格式化为字符串会更快呢?这样可以减少字符串转换。 - Vatine
@Vatine 感谢您的解释。使用时间比较 23:59:60 将无法通过日期时间验证,会抛出异常,我认为这是一个好的方法,因为可以处理异常并向用户呈现消息。另一方面,使用字符串比较将不会验证任何内容,并且会“错误地”将 00:00:00 显示为早于 23:59:60 的时间。 - felipeptcho
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接