Skip to main content
 首页 » 编程设计

Python 不比较日期

2025年05月04日11duanxz

我有这个启动时间:

2015-01-15 10:31:54+00:00

我得到当前时间

current_time = datetime.datetime.now(launch_time.tzinfo) 

我希望两次都相同,所以我使用了 tzinfo。所以,current_time的值为

2015-01-16 10:55:50.200571+00:00

我用这个来计算运行时间:

running_time = (current_time - launch_time).seconds/60 

该值仅返回 23 分钟。应该是一天 + 23 分钟 = 1463 分钟

谁能帮帮我。谢谢

请您参考如下方法:

您忽略了返回的 timedelta 对象的 .days 属性。使用 timedelta.total_seconds()而不是将它们包含在一个值中:

running_time = (current_time - launch_time).total_seconds()/60 

或者如果您想忽略增量的微秒部分,则显式使用它:

running_time = current_time - launch_time.total_seconds() 
running_time = running_time.seconds / 60 + running_time.days / 1440 

来自documentation for timedelta.total_seconds() :

Return the total number of seconds contained in the duration. Equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 computed with true division enabled.