英文:
How do i subtarct 2 time columns with each other in Python?
问题
我有一个列 Start 和 HT,它们都是对象数据类型:
需要的输出是(HT - Start)的分钟数。
我尝试通过 pd.to_datetime 将它们转换为日期时间,但会抛出错误
TypeError: <class 'datetime.time'> 无法转换为日期时间
| Start | HT |
| -------- | ------ |
| 09:30:00| 09:40:00|
| 09:30:00| 09:36:00|
| 09:30:00| 09:50:00|
| 09:30:00| 10:36:00|
期望输出
| Start | HT | 差异(分钟) |
| -------- | ------ |---- |
| 09:30:00| 09:40:00| 10 |
| 09:30:00| 09:36:00| 6 |
| 09:30:00| 09:50:00| 20 |
| 09:30:00| 10:36:00| 66 |
请帮忙。
英文:
I have a column Start and HT where both are Object Datatype:
The output which is needed is (HT - Start) in minutes.
I try to convert them to datetime through pd.to_datetime but it throws error
TypeError: <class 'datetime.time'> is not convertible to datetime
Start | HT |
---|---|
09:30:00 | 09:40:00 |
09:30:00 | 09:36:00 |
09:30:00 | 09:50:00 |
09:30:00 | 10:36:00 |
Expected Output
Start | HT | diff(in minutes) |
---|---|---|
09:30:00 | 09:40:00 | 10 |
09:30:00 | 09:36:00 | 6 |
09:30:00 | 09:50:00 | 20 |
09:30:00 | 10:36:00 | 66 |
Please help.
答案1
得分: 1
你可以首先使用 pd.to_datetime()
转换日期:
df['Start'] = pd.to_datetime(df['Start'], format='%H:%M:%S').dt.time.apply(str)
df['HT'] = pd.to_datetime(df['HT'], format='%H:%M:%S').dt.time.apply(str)
df['diff(in minutes)'] = (pd.to_timedelta(df['HT']) - pd.to_timedelta(df['Start'])).dt.total_seconds() / 60
print(df)
你可以使用 pd.to_timedelta()
简化上面的代码:
df['Start'] = pd.to_timedelta(df['Start'])
df['HT'] = pd.to_timedelta(df['HT'])
df['diff(in minutes)'] = (df['HT'] - df['Start']).dt.total_seconds() / 60
print(df)
Start HT diff(in minutes)
0 09:30:00 09:40:00 10.0
1 09:30:00 09:36:00 6.0
2 09:30:00 09:50:00 20.0
3 09:30:00 10:36:00 66.0
英文:
You should fisrt convert dates using pd.to_datetime()
df['Start'] = pd.to_datetime(df['Start'], format='%H:%M:%S').dt.time.apply(str)
df['HT'] = pd.to_datetime(df['HT'], format='%H:%M:%S').dt.time.apply(str)
df['diff(in minutes)'] = (pd.to_timedelta(df['HT']) - pd.to_timedelta(df['Start'])).dt.total_seconds() / 60
print(df)
You can simplify the above code using pd.to_timedelta()
df['Start'] = pd.to_timedelta(df['Start'])
df['HT'] = pd.to_timedelta(df['HT'])
df['diff(in minutes)'] = (df['HT'] - df['Start']).dt.total_seconds() / 60
print(df)
Start HT diff(in minutes)
0 09:30:00 09:40:00 10.0
1 09:30:00 09:36:00 6.0
2 09:30:00 09:50:00 20.0
3 09:30:00 10:36:00 66.0
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论