Find difference between list of dates in python

Viewed 2197

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.

3 Answers

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]

Since that is list we can using list operation

[(t - s).days for s, t in zip(l, l[1:])]
Out[137]: [0, 1, 10, 2, 1, 8, 0, 2, 2, 0]

Since pandas is tagged where l is your list , you can use: series.diff():

pd.Series(l).diff().dt.days.dropna().tolist()

[0.0, 1.0, 10.0, 2.0, 1.0, 8.0, 0.0, 2.0, 2.0, 0.0]
Related