[英]Python calculating time difference, to give ‘years, months, days, hours, minutes and seconds’ in 1
我想知道“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
它給出了天數的差異。
我還能做什么? 我怎樣才能達到想要的結果?
使用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 年”而不是“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 實例方法:
timdelta 類屬性是:
您可以使用days
和seconds
實例屬性來計算您需要的內容。
例如:
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.