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

2024-05-02 03:55:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我在找两次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")

Tags: 字符串importiftime格式计算机时间this
3条回答

https://docs.python.org/2/library/datetime.html

datetime模块将把日期、时间或组合的日期时间值解析为可比较的对象。

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

相关问题 更多 >