如何在Python中将两个时间列相互相减?

huangapple go评论80阅读模式
英文:

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[&#39;Start&#39;] = pd.to_datetime(df[&#39;Start&#39;], format=&#39;%H:%M:%S&#39;).dt.time.apply(str)
df[&#39;HT&#39;] = pd.to_datetime(df[&#39;HT&#39;], format=&#39;%H:%M:%S&#39;).dt.time.apply(str)
df[&#39;diff(in minutes)&#39;] = (pd.to_timedelta(df[&#39;HT&#39;]) - pd.to_timedelta(df[&#39;Start&#39;])).dt.total_seconds() / 60
print(df)

You can simplify the above code using pd.to_timedelta()

df[&#39;Start&#39;] = pd.to_timedelta(df[&#39;Start&#39;])
df[&#39;HT&#39;] = pd.to_timedelta(df[&#39;HT&#39;])
df[&#39;diff(in minutes)&#39;] = (df[&#39;HT&#39;] - df[&#39;Start&#39;]).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

huangapple
  • 本文由 发表于 2023年2月14日 22:30:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75449294.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定