Python计算时差,以1表示“年,月,日,小时,分钟和秒” [英] Python calculating time difference, to give ‘years, months, days, hours, minutes and seconds’ in 1
本文介绍了Python计算时差,以1表示“年,月,日,小时,分钟和秒”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道在'2014-05-06 12:00:56'和'2012-03-06 16:08:22'之间的年,月,日,小时,分钟和秒。结果应类似于:差异为xxx年xxx月xxx天xxx小时xxx分钟
I want to know how many years, months, days, hours, minutes and seconds in between '2014-05-06 12:00:56' and '2012-03-06 16:08:22'. The result shall looked like: "the difference is xxx year xxx month xxx days xxx hours xxx minutes"
例如:
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
以天为单位给出差值。
It gives the difference in days.
我还能做什么?以及如何获得所需的结果?
What else I can do? And how can I achieve the wanted result?
推荐答案
使用 relativedelta
来自 dateutil软件包。
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年。
You might want to add some logic to print for e.g. "2 years" instead of "2 year".
这篇关于Python计算时差,以1表示“年,月,日,小时,分钟和秒”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文