简体   繁体   English

Python计算时差,在1中给出“年、月、日、时、分和秒”

[英]Python calculating time difference, to give ‘years, months, days, hours, minutes and seconds’ in 1

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'.我想知道“2014-05-06 12:00:56”和“2012-03-06 16:08:22”之间有多少年、月、日、小时、分钟和秒。 The result shall looked like: “the difference is xxx year xxx month xxx days xxx hours xxx minutes”结果应如下所示:“差异为 xxx 年 xxx 月 xxx 天 xxx 小时 xxx 分钟”

For example:例如:

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

if I do:如果我做:

diff.days

It gives the difference in days.它给出了天数的差异。

What else I can do?我还能做什么? And how can I achieve the wanted result?我怎样才能达到想要的结果?

Use a relativedelta from the dateutil package .使用dateutil 包中relativedelta增量 This will take into account leap years and other quirks.这将考虑闰年和其他怪癖。

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

You might want to add some logic to print for eg "2 years" instead of "2 year".您可能想要添加一些逻辑来打印例如“2 年”而不是“2 年”。

diff is a timedelta instance. diff 是一个timedelta实例。

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

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

from docs:来自文档:

timdelta instance attributes (read-only): timdelta 实例属性(只读):

  • days
  • seconds
  • microseconds微秒

timdelta instance methods: timdelta 实例方法:

  • total_seconds() total_seconds()

timdelta class attributes are: timdelta 类属性是:

  • min分钟
  • max最大限度
  • resolution解析度

You can use the days and seconds instance attributes to calculate what you need.您可以使用daysseconds实例属性来计算您需要的内容。

for example:例如:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM