python - 如何解析超过一个月长度的天数?

标签 python datetime strptime strftime

我制作了一个倒计时函数(效果很好),它以字符串形式返回剩余时间。我使用 strptimestrftime 函数对数据进行排序分析,这样我就可以有一个变量来表示剩余的天数、小时数、分钟数和秒数。一旦天数超过 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/

相关文章:

python - 如何在Django模型中同步更新实例?

python - 了解 softmax 输出层的目标数据

C#,NUnit : Is it possible to test that a DateTime is very close, 但不一定等于另一个?

c# - 计算给定时间段内的正常工作日

python - 在python中将日期从数据集转换为yyyy-mm-dd

date - Time::Piece strptime 遇到 %X 问题

python - 将日期时间转换为 strptime

python - 如何在 Azure Web 应用程序上运行 apt-get 或在 azure 上的 Flask 中导入 cv2?

r - 在 R 中处理整数时间

python - 如何将日期选择器放入 django 应用程序中?