Python计算时差,给出'年,月,日,小时,分钟和秒'1

时间:2014-08-22 03:53:14

标签: python datetime

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

它给出了天数的差异。

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

2 个答案:

答案 0 :(得分:25)

使用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年”。

答案 1 :(得分:6)

diff是timedelta个实例。

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

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

来自docs:

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)