python - 计算熊猫数据帧中两个日期时间戳 [yyyy-mm-dd hh:mm:ss.000] 列之间的差异(以秒为单位)时出错
问题描述
我有一个数据框,它有两列“Etime”和“Stime”,其中包含结束和开始时间戳,其示例如下所示:
df = pd.DataFrame({'Etime': ['2019-08-23 00:00:06.773', '2019-09-19 00:00:16.083', '2019-08-29 00:00:07.043', '2019-10-01 00:00:14.777','2019-08-15 00:00:57.050'],
'Stime': ['2019-08-22 23:59:41.983', '2019-09-18 23:59:44.007', '2019-08-28 23:59:02.863', '2019-09-30 23:59:05.187', '2019-08-14 23:59:20.217']})
我想做的是创建另一个列“持续时间”,该列应包含开始和结束时间的差异(以秒为单位),最终数据集应如下所示:
Etime Stime Duration
2019-08-23 00:00:06.773 2019-08-22 23:59:41.983 25
2019-09-19 00:00:16.083 2019-09-18 23:59:44.007 32
2019-08-29 00:00:07.043 2019-08-28 23:59:02.863 04
2019-10-01 00:00:14.777 2019-09-30 23:59:05.187 10
2019-08-15 00:00:57.050 2019-08-14 23:59:20.217 37
我想做的是:
df['STS'] = pd.to_timedelta(pd.to_datetime(df['Stime']).dt.time.astype(str)).dt.total_seconds()
df['EDS'] = pd.to_timedelta(pd.to_datetime(df['Etime']).dt.time.astype(str)).dt.total_seconds()
df['Duration'] = round(df['EDS'] - df['STS'], 0)
这给了我错误的输出如下:
Etime Stime Duration
2019-08-23 00:00:06.773 2019-08-22 23:59:41.983 -86375
2019-09-19 00:00:16.083 2019-09-18 23:59:44.007 -86368
2019-08-29 00:00:07.043 2019-08-28 23:59:02.863 -86336
2019-10-01 00:00:14.777 2019-09-30 23:59:05.187 -86330
2019-08-15 00:00:57.050 2019-08-14 23:59:20.217 -86303
我在这里做错了什么?
有没有更好的方法呢?
解决方案
试试这个:
date_format = '%Y-%m-%d %H:%M:%S.%f'
df['Duration'] = [(datetime.strptime(df.loc[x,'Etime'], date_format ) -
datetime.strptime(df.loc[x,'Stime'], date_format)).seconds
for x in df.index]
推荐阅读
- javascript - 如何检查 URL 是否具有匹配的结尾作为 json 字符串
- php - WooCommerce 从订单项中获取产品变体属性名称和值
- raspberry-pi - Raspberry PI,无法使用 NTFS 分区硬盘复制、修改或写入 NAS 上的文件
- javascript - 如何解决“参数列表后未捕获的语法错误:缺少)”问题
- sql - 如何将数值表的所有列除以 SQL Server 中的最后一列,除了 ID 列和最后一列作为除数?
- r - replacement has length zero error in R programming of a no claim discount scheme
- azure-devops - 条件 OR 与 Azure Devops Pipeline 中的变量
- javascript - Android App crashes on starting new activity when there is background image
- python - Euler explicit in Fourier space
- javascript - How to receive data attribute with jsoup?