gpt4 book ai didi

Python:时间日期问题

转载 作者:太空宇宙 更新时间:2023-11-03 18:17:45 24 4
gpt4 key购买 nike

我一直在制作一个特定时间的小型倒计时器,但它似乎存在负数天数的问题。示例:

s1 = '14:00:00'
s2 = str(current_time)
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s1, FMT) - datetime.strptime(s2, FMT)
print tdelta
>>>-1 day, 22:34:23

Current_time 是我的系统时间

如何删除-1天?字符串(s1s2)都没有日期,因此它在 tdelta 变量计算中生成这一天的数字。

最佳答案

如果您知道目标时间应该是哪一天(例如 2014 年 8 月 1 日),请使用它:

import datetime
target_time = datetime.datetime(2014, 8, 1, 14, 0, 0)
now = datetime.datetime.now()
time_to_go = target_time - now
print(time_to_go)

如果目标时间是今天,您可以只更改小时、分钟和秒,其余部分保留今天的日期:

import datetime
target_time = datetime.datetime.now().replace(hour=14, minute=0, second=0, microsecond = 0)
now = datetime.datetime.now()
time_to_go = target_time - now
print(time_to_go)

如果 target_time 在当前时间之前,timedelta 对象会使用递减的负日和正秒来跟踪负时间,从而增加负差异,从而增加与 target_time 的时间距离。

如果您始终想要跟踪给定小时的时间,无论是哪一天,请使用:

import datetime
target_time = datetime.datetime.now().replace(hour=14, minute=0, second=0, microsecond = 0)
now = datetime.datetime.now()
if target_time < now:
target_time += datetime.timedelta(1)
time_to_go = target_time - now
print(time_to_go)

关于Python:时间日期问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24738919/

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