2017-10-14 55 views
0

我試圖計算Python中兩個日期之間的差異,並用天,周,月和年表示這個時間差。Python:兩次之差

我的Python代碼如下:

purDate = datetime.datetime.strptime(queryPurchaseDate (purID), "%Y-%m-%d %H:%M:%S") 
    now = datetime.datetime.now() 

    print 'Purchase date/time : ',purDate.strftime("%Y-%m-%d %H:%M:%S") 
    print 'Current date/time : ',now.strftime("%Y-%m-%d %H:%M:%S") 

    hold = now - purDate  

    print hold 

此代碼的結果如下:

bash-3.2$ ./test.py 
Purchase date/time : 2017-10-10 00:00:00 
Current date/time : 2017-10-14 17:33:39 
4 days, 17:33:39.866069 
bash-3.2$ 

代替具有兩個日期之間的差的表示爲 4天,17 :33:39.866069 我想表達如下: 4.65天或 0.66周或 0.15個月或 0.01歲

回答

2

兩個datetime對象之間的差異是一個timedelta對象。您可以在幾秒鐘內表達這種差異,然後在一天/一週/一年/一年中使用總秒數的定義來計算您的比率。

>>> diff = timedelta(days=4, seconds=17 * 3600 + 33 * 60 + 39.866069) 
>>> print(diff) 
4 days, 17:33:39.866069 
>>> diff.total_seconds()/86400 
4.731711412835648 
>>> diff.total_seconds()/(86400 * 7) 
0.6759587732622354 
>>> diff.total_seconds()/(86400 * 30) 
0.15772371376118827 
>>> diff.total_seconds()/(86400 * 365) 
0.012963592911878487 

這種方法稍微簡單一些,因爲它沒有考慮月份或閏年的不規律性。 365和366天之間的差異不應顯示在您想要的準確度內,因此您可以忽略它。對於這幾個月,你是否希望30天保持一個月的連續性,或者你希望在2017年1月8日至2017年1月9日之間登記爲一個月?這會使事情變得複雜,精確度至多提高0.01。

def timedelta_to(time_diff, unit='day'): 
    options = {'day': 86400, 
     'week': 86400 * 7, 
     'month': 86400 * 30, 
     'year': 86400 * 365, 
     } 
    # default to days for an invalid unit of choice, 
    # though warning to user might be another option 
    if unit not in options: 
     unit = 'day' 
    duration = time_diff.total_seconds()/options[unit] 
    return '{0:.2f} {1}s'.format(duration, unit.title()) 

你可以像這樣使用它。

>>> timedelta_to(diff) 
'4.73 Days' 
>>> timedelta_to(diff, 'month') 
'0.16 Months' 
+0

這樣比較好。我不知道這個差別是默認的'timedelta' – akilat90

1

可以使用熊貓轉換爲timedelta對象,然後進行後續的數學運算

delta = pd.Timedelta(delta) 
delta.total_seconds()/(24*60*60) # this will give the timedelta in days 

演示

import pandas as pd 
import datetime 

time1 = datetime.datetime.now() 
time2 = '2017-10-01 00:00:00' 
time2 = pd.to_datetime(time2) 

delta = time1 - time2 
print(delta) 
13 days 22:03:50.081000 

delta = pd.Timedelta(delta) 
print(delta.total_seconds()/(24*60*60)) 
13.909289537037038 

編輯:

不需要使用熊貓。正如@Reti43解釋的那樣,您可以使用delta.total_seconds()/(24*60*60)