2016-12-17 4 views
4

私は月の下の日付1と日付2の間を月に取得しようとしています。結果は単に2016-12から2016-5を引いたものです。これは7です。私はintで日数を取得する方法しか知りません。誰かがmthsの結果を7に取得する方法を教えてくれますか?月の月を引く月

import pandas as pd 
import numpy as np 

date1=pd.to_datetime('2016-12-1') 
date2=pd.to_datetime('2016-5-27') 

print((date1-date2)/np.timedelta64(1,'D')) 
+0

月になる標準単位ではありません。月に30日かかるとしたら、 '(date1 - date2).days/30'とすることができます – ayhan

+0

あなたのすべての日付は同じ年ですか? – doctorlove

+0

私の日付は異なる年ですが、SQLの同等の 'datediff(month、date1、date2)'があると思っていました – unclegood

答えて

5

あなたはヶ月間に日付を変換してから減算を行うことができます。

date1.to_period("M") - date2.to_period("M") 
# 7 
+0

これは列に対して機能しますか?私は上記のデータフレームで2つの列を使用し、次のエラーがあります。AttributeError: 'Index'オブジェクトに 'to_period'属性がありません – unclegood

+1

これは列に適用されますが、これらの列がdatetime型であることを確認する必要があります'pd.to_datetime()'を使って変換します。また、datetimeカラム( '.dt'アクセサが必要)を扱う方法はdatetimeインデックスとは異なります。 – Psidom

+0

はい、私は.dtを追加した後に動作します、ありがとう! – unclegood

2

あなたは月内の日を気にしない場合は、次のように行うことができます。

date1.year * 12 + date1.month - (date2.year * 12 + date2.month) 

同じ月の日付'2016-12-31 'と'2016-12-1'は0を返します。

月の中の日を計算したい場合は、指定されるまでの月の割合を計算できます日。例えば。月に30日がある場合、最初の日の分数は0/30で、最後の日の分数は29/30です。 このコードスニペットは、それを行います。

from calendar import monthrange 

def get_frac_of_month(date): 
    # monthrange returns a tuple where the second entry is the number of days in the month 
    return 1. * (date.day - 1)/monthrange(date.year, date.month)[1] 

def get_month_diff(date1, date2): 
    return date1.year * 12 + date1.month + get_frac_of_month(date1) - (date2.year * 12 + date2.month + get_frac_of_month(date2)) 

print get_month_diff(date1, date2) 

出力に含まが

6.16129032258