gpt4 book ai didi

全天、全小时等的 Python timedelta

转载 作者:行者123 更新时间:2023-11-28 20:04:23 27 4
gpt4 key购买 nike

我想要一些如何打印消息,例如:“从那时起,已经过去了 x 天、y 小时、z 分钟和 w 秒”。目前我正在做这样的事情,但我想念剩下的部分(最重要的是)我不喜欢它。应该有更美的东西

dt = (datetime.now() - datetime(year=1980, month=1, day=1, hour=18)).total_seconds()
full_days = int(dt // (3600 * 24))
full_hours = int((dt - full_days * (24 * 3600)) // 3600)
full_minutes = int((dt - full_days * (24 * 3600) - full_hours * 3600) // 60)
residual_seconds = dt - full_days * (24 * 3600) - full_hours * 3600 - full_minutes * 60
print(full_days, full_hours, full_minutes, residual_seconds)

最佳答案

您可以使用 timedelta :

from datetime import datetime

fmt = 'Since then, {0} days, {1} hours, {2} minutes and {3} seconds have elapsed'
td = datetime.now() - datetime(year=1980, month=1, day=1, hour=18)
print(fmt.format(td.days, td.seconds // 3600, td.seconds % 3600 // 60, td.seconds % 60))

输出:

Since then, 13266 days, 23 hours, 5 minutes and 55 seconds have elapsed

关于全天、全小时等的 Python timedelta,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36909818/

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