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

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

How do i subtarct 2 time columns with each other in Python?

问题

  1. 我有一个列 Start HT,它们都是对象数据类型:
  2. 需要的输出是(HT - Start)的分钟数。
  3. 我尝试通过 pd.to_datetime 将它们转换为日期时间,但会抛出错误
  4. TypeError: <class 'datetime.time'> 无法转换为日期时间
  5. | Start | HT |
  6. | -------- | ------ |
  7. | 09:30:00| 09:40:00|
  8. | 09:30:00| 09:36:00|
  9. | 09:30:00| 09:50:00|
  10. | 09:30:00| 10:36:00|
  11. 期望输出
  12. | Start | HT | 差异(分钟) |
  13. | -------- | ------ |---- |
  14. | 09:30:00| 09:40:00| 10 |
  15. | 09:30:00| 09:36:00| 6 |
  16. | 09:30:00| 09:50:00| 20 |
  17. | 09:30:00| 10:36:00| 66 |
  18. 请帮忙。
英文:

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() 转换日期:

  1. df['Start'] = pd.to_datetime(df['Start'], format='%H:%M:%S').dt.time.apply(str)
  2. df['HT'] = pd.to_datetime(df['HT'], format='%H:%M:%S').dt.time.apply(str)
  3. df['diff(in minutes)'] = (pd.to_timedelta(df['HT']) - pd.to_timedelta(df['Start'])).dt.total_seconds() / 60
  4. print(df)

你可以使用 pd.to_timedelta() 简化上面的代码:

  1. df['Start'] = pd.to_timedelta(df['Start'])
  2. df['HT'] = pd.to_timedelta(df['HT'])
  3. df['diff(in minutes)'] = (df['HT'] - df['Start']).dt.total_seconds() / 60
  4. print(df)

  1. Start HT diff(in minutes)
  2. 0 09:30:00 09:40:00 10.0
  3. 1 09:30:00 09:36:00 6.0
  4. 2 09:30:00 09:50:00 20.0
  5. 3 09:30:00 10:36:00 66.0
英文:

You should fisrt convert dates using pd.to_datetime()

  1. df[&#39;Start&#39;] = pd.to_datetime(df[&#39;Start&#39;], format=&#39;%H:%M:%S&#39;).dt.time.apply(str)
  2. df[&#39;HT&#39;] = pd.to_datetime(df[&#39;HT&#39;], format=&#39;%H:%M:%S&#39;).dt.time.apply(str)
  3. df[&#39;diff(in minutes)&#39;] = (pd.to_timedelta(df[&#39;HT&#39;]) - pd.to_timedelta(df[&#39;Start&#39;])).dt.total_seconds() / 60
  4. print(df)

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

  1. df[&#39;Start&#39;] = pd.to_timedelta(df[&#39;Start&#39;])
  2. df[&#39;HT&#39;] = pd.to_timedelta(df[&#39;HT&#39;])
  3. df[&#39;diff(in minutes)&#39;] = (df[&#39;HT&#39;] - df[&#39;Start&#39;]).dt.total_seconds() / 60
  4. print(df)

  1. Start HT diff(in minutes)
  2. 0 09:30:00 09:40:00 10.0
  3. 1 09:30:00 09:36:00 6.0
  4. 2 09:30:00 09:50:00 20.0
  5. 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:

确定