Search code examples
pythonpandaspython-datetime

Find difference between list of dates in python


I want to find difference between list of dates in days.

I have a list of Timestamp object.

[Timestamp('2016-10-18 00:00:00'), Timestamp('2016-10-18 00:00:00'), Timestamp('2016-10-19 00:00:00'), Timestamp('2016-10-29 00:00:00'), Timestamp('2016-10-31 00:00:00'), Timestamp('2016-11-01 00:00:00'), Timestamp('2016-11-09 00:00:00'), Timestamp('2016-11-09 00:00:00'), Timestamp('2016-11-11 00:00:00'), Timestamp('2016-11-13 00:00:00'), Timestamp('2016-11-13 00:00:00')]

And I want the following result

[0,1,10,2,1,8,0,2,2,0]

I tried the following code but I am getting compilation error "TypeError: 'Timestamp' object is not iterable"

def calculateInterOrderTime(dateList):
   result = map(lambda x: [i / np.timedelta64(1, 'D') for i in np.diff([c for c in x])[0]],dateList)
   print(list(result))

It will be great if someone can help me with my lambda expression to do what I want.


Solution

  • Use Series constructor, Series.diff, Series.dt.days, remove first value by Series.iloc, convert to integers and then to lists:

    print (pd.Series(dateList).diff().dt.days.iloc[1:].astype(int).tolist())
    [0, 1, 10, 2, 1, 8, 0, 2, 2, 0]
    

    Your solution should be changed with DatetimeIndex, so is possible divide all values without list comprehension:

    print ((np.diff(pd.DatetimeIndex(dateList)) / np.timedelta64(1, 'D')).astype(int).tolist())
    [0, 1, 10, 2, 1, 8, 0, 2, 2, 0]