在python中,如何减去excel文件中具有时间值的两列并创建新的列?

2024-04-19 08:18:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个excel数据库,如下所示:

ExcelTimeData

我想使用python获得新列(ResponseTime)=(endtimestarttime)。我正在使用以下python代码:

     import pandas as pd
     import numpy as np
     from matplotlib import pyplot as plt
     new = pd.read_excel("single_file.xlsx") 
     sf=pd.DataFrame(new)
     sf['Res_Time'] = sf['EndTime'] - sf['StartTime'])

它向我显示了以下错误:

TypeError: unsupported operand type(s) for -: 'str' and 'str'

如何在两列中减去时间值


Tags: 代码importnumpy数据库pandasnewasnp
1条回答
网友
1楼 · 发布于 2024-04-19 08:18:44

您试图减去两个字符串,为了首先处理日期,必须使用^{}将列转换为datetime

sf['EndTime'] = pd.to_datetime(sf['EndTime'], format='%H:%M:%S')
sf['StartTime'] = pd.to_datetime(sf['StartTime'], format='%H:%M:%S')

使用format,您可以更改字符串解析,检查strftime

相关问题 更多 >