python - 在python中查找日期列表之间的差异

标签 python pandas python-datetime

我想找出以天为单位的日期列表之间的差异。

我有一个时间戳对象列表。

[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')]

我想要下面的结果

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

我尝试了以下代码,但出现编译错误“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))

如果有人能帮助我用 lambda 表达式做我想做的事,那就太好了。

最佳答案

使用 Series 构造函数,Series.diff , Series.dt.days , 通过 Series.iloc 删除第一个值,转换为整数,然后转换为列表:

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

您的解决方案应更改为 DatetimeIndex,因此可以在不理解列表的情况下划分所有值:

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

关于python - 在python中查找日期列表之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56462913/

相关文章:

python - 值错误: Location based indexing can only have [labels (MUST BE IN THE INDEX)

没有复制的 Pandas 数据框

Python 字典到 Pandas 数据框

python - 未指定的未转换数据是什么意思?

python - 将 datetime.datetime 对象写入文件

python - Twilio 'ConferenceSid'是如何生成的?

python - 从两列随机生成唯一组合

python - 如何使用python根据同一数据框中另一列的值对数据框中的列中的值进行排序

python - 我需要明确等待吗?

python - 更改 matplotlib 中日期时间轴的格式