Pandas Datetime: Calculate Number of Weeks Between Dates in Two Columns

前端 未结 2 833
眼角桃花
眼角桃花 2021-01-03 08:37

Let\'s say I have a dataframe with two columns that contain dates, and I want to create a new columns whose value is the number of months between those dates.



        
相关标签:
2条回答
  • 2021-01-03 08:53

    I'm not sure how to do it in python but the steps I would do:

    • Convert dates into number of days since the epoch
    • Subtract date1 from date2
    • Divide by 7
    0 讨论(0)
  • 2021-01-03 08:58

    see this link: http://pandas.pydata.org/pandas-docs/dev/timeseries.html#time-deltas

    (df['Date2']-df['Date1']).apply(lambda x: x/np.timedelta64(1,'M'))
    

    for numpy >=1.7 (see the link if you are using 1.6.1)

    I am not sure what it will do with the fraction. (usually I would divide by np.timedelta64(1,'D') then divide by say 30 to make a fractional num of months (as a float)

    0 讨论(0)
提交回复
热议问题