我制作了一个倒计时函数(效果很好),它以字符串形式返回剩余时间。我使用 strptime
和 strftime
函数对数据进行排序分析,这样我就可以有一个变量来表示剩余的天数、小时数、分钟数和秒数。一旦天数超过 31(因为月份),我的代码就会出现错误。我有什么办法可以解决这个问题吗?
from datetime import datetime, date
a = "31 days, 23:52:51"
b = "32 days, 23:52:51"
d = datetime.strptime(b, "%d days, %H:%M:%S")
t1 = d.strftime("%d")
t2 = d.strftime("%H")
t3 = d.strftime("%M")
t4 = d.strftime("%S")
print(t1)
print(t2)
print(t3)
print(t4)
最佳答案
没有一个月有 32 天,因此您的错误。然而,对于时差,只需使用timedelta
。您可以自由地将时间增量添加到 datetime
对象。
import re
from datetime import datetime, timedelta
now = datetime.now()
r = "^(\d+) days?, (\d+):(\d+):(\d+)$"
cases = ["1 day, 11:12:13", "31 days, 23:52:51", "32 days, 23:52:51"]
for s in cases:
m = re.match(r, s)
days, hours, minutes, seconds = [int(x) for x in m.groups()]
td = timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
print(td) # gives you the intended output (use str(td) if you want the string)
# the code below duplicates that print manually
days2 = td.days
hours2, seconds2 = divmod(td.seconds, 3600)
minutes2, seconds2 = divmod(seconds2, 60)
print(f'{days2} day{"s" if 1 < days2 else ""}, {hours2}:{minutes2:0>2}:{seconds2:0>2}')
# and finally the print of the datetime object made of current time plus our time delta
print(now+td)
输出(将根据您的时钟而变化):
1 day, 11:12:13
1 day, 11:12:13
2021-08-12 23:23:33.986973
31 days, 23:52:51
31 days, 23:52:51
2021-09-12 12:04:11.986973
32 days, 23:52:51
32 days, 23:52:51
2021-09-13 12:04:11.986973
关于python - 如何解析超过一个月长度的天数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68739612/