Python计算时间差,输出‘年、月、日、小时、分钟和秒’

22 投票
3 回答
33180 浏览
提问于 2025-04-18 18:09

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

它给出的只是天数的差距。

那我还可以做些什么呢?我该怎么才能得到想要的结果呢?

3 个回答

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秒

10

diff是一个timedelta实例。

关于Python 2,可以查看: https://docs.python.org/2/library/datetime.html#timedelta-objects

关于Python 3,可以查看: 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)
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 years”而不是“2 year”。

撰写回答