Python计算时间差,输出“年、月、日、小时、分钟和秒”在1中。

22

我想知道在“2014-05-06 12:00:56”和“2012-03-06 16:08:22”之间相差多少年、月、日、小时、分钟和秒。结果应该是:“相差 xxx 年 xxx 月 xxx 天 xxx 小时 xxx 分钟”。

例如:

import datetime

a = '2014-05-06 12:00:56'
b = '2013-03-06 16:08:22'

start = datetime.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
ends = datetime.datetime.strptime(b, '%Y-%m-%d %H:%M:%S')

diff = start – ends

如果我这样做:

diff.days

它给出了天数差异。

我还能做什么?我如何达到想要的结果?


1
可能是理解timedelta的重复问题。 - metatoaster
3个回答

36
使用从 dateutil 包 中的 relativedelta,这将考虑闰年和其他细节。
import datetime
from dateutil.relativedelta import relativedelta

a = '2014-05-06 12:00:56'
b = '2013-03-06 16:08:22'

start = datetime.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
ends = datetime.datetime.strptime(b, '%Y-%m-%d %H:%M:%S')

diff = relativedelta(start, ends)

>>> print "The difference is %d year %d month %d days %d hours %d minutes" % (diff.years, diff.months, diff.days, diff.hours, diff.minutes)
The difference is 1 year 1 month 29 days 19 hours 52 minutes

你可能想要添加一些逻辑,以便打印“2年”而不是“2年”。


10

diff是一个timedelta实例。

对于Python2,请参见:https://docs.python.org/2/library/datetime.html#timedelta-objects

对于Python3,请参见:https://docs.python.org/3/library/datetime.html#timedelta-objects

来自文档:

timedelta实例属性(只读):

  • days
  • seconds
  • microseconds

timedelta实例方法:

  • total_seconds()

timedelta类属性包括:

  • min
  • max
  • resolution

您可以使用daysseconds实例属性来计算所需内容。

例如:

import datetime

a = '2014-05-06 12:00:56'
b = '2013-03-06 16:08:22'

start = datetime.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
ends = datetime.datetime.strptime(b, '%Y-%m-%d %H:%M:%S')

diff = start - ends

hours = int(diff.seconds // (60 * 60))
mins = int((diff.seconds // 60) % 60)

谢谢,Corey Goldberg。您的原始回复也非常有用。 - Mark K
1
这个例子不起作用,它说两个日期之间的差异只有19小时...显然,'2014-05-06'和'2013-03-06'不是这种情况。 - tong
Tong,因为他使用了“秒”,所以排除了使用“天”计算的数量,因此应该是diff.days ( = 425) 加上那19小时。 - Andrei

1

计算时间戳之间的差异:

from time import time

def timestamp_from_seconds(seconds):
    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)
    days, hours = divmod(hours, 24)
    return days, hours, minutes, seconds

print("\n%d days, %d hours, %d minutes, %d seconds" % timestamp_from_seconds(abs(1680375128- time())))

输出:1天,19小时,19分钟,55秒


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接