gpt4 book ai didi

Python当前时间与其他时间对比

转载 作者:太空狗 更新时间:2023-10-30 02:41:22 24 4
gpt4 key购买 nike

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

关于Python当前时间与其他时间对比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39585338/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com