【问题标题】:Python calculating time difference, to give ‘years, months, days, hours, minutes and seconds’ in 1Python计算时差,在1中给出“年、月、日、小时、分钟和秒”
【发布时间】:2014-08-22 03:53:14
【问题描述】:

我想知道“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

它给出了天数的差异。

我还能做什么?我怎样才能达到想要的结果?

【问题讨论】:

标签: python datetime


【解决方案1】:

使用dateutil package 中的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 年”。

【讨论】:

    【解决方案2】:

    diff 是一个timedelta 实例。

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

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

    来自文档:

    timdelta 实例属性(只读):

    • 微秒

    timdelta 实例方法:

    • total_seconds()

    timdelta 类属性为:

    • 分钟
    • 最大
    • 分辨率

    您可以使用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)
    

    【讨论】:

    • 谢谢,科里·戈德堡。你原来的回复也很有用。
    • 这个例子不起作用,它说这两个日期之间的差异只有 19 小时......显然,'2014-05-06' 和 '2013-03-06' 不是这种情况.
    猜你喜欢
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 2012-01-19
    • 2011-07-26
    • 2021-09-17
    • 2018-08-24
    • 2020-05-20
    相关资源
    最近更新 更多