如何在HH:MM的时间中添加以小时为单位的持续时间,并在新列中获取它?

2024-04-23 23:44:53 发布

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

示例:

Start Date   Start Time   Duration (hours)
------------------------------------------
8/15/2016       3:10        15.58
------------------------------------------
8/16/2016       6:50        29.67
-----------------------------------------
7/28/2016       1:30        8.17
-----------------------------------------

如何获得名为“结束日期”和“结束时间”的新列,这是将“持续时间(小时)”添加到“开始时间”的结果?你知道吗

期望输出:

例如,假设有降雨记录:

开始日期:8/15/2016 开始时间:03:10(HH:MM)

如果降雨持续时间是15.58小时,那么结束日期和结束时间是多少?这是为数据帧中具有不同时间和持续时间的许多类似事件计算的。你知道吗

因此,所需的输出应如下所示:

 Start Date   Start Time   Duration (hours)   End Date      End Time 
--------------------------------------------------------------------
8/15/2016       3:10        15.58         8/15/2016      19:08
--------------------------------------------------------------------

Tags: 数据示例datetimehh记录时间start
1条回答
网友
1楼 · 发布于 2024-04-23 23:44:53

似乎您需要转换^{}^{},对于提取datestimes使用^{}^{}

df['Start Date'] = pd.to_datetime(df['Start Date'])
Start =  pd.to_timedelta(df['Start Time'] + ':00', unit='h')
Duration =  pd.to_timedelta(df['Duration (hours)'].astype(str)
                                                  .str.replace('.',':') + ':00', unit='h')

End = df['Start Date'] + Start + Duration
df['End Date'] = End.dt.date
#str[:5] remove seconds
df['End Time'] = End.dt.time.astype(str).str[:5]

print (df)
  Start Date Start Time  Duration (hours)    End Date End Time
0 2016-08-15       3:10             15.58  2016-08-15    19:08
1 2016-08-16       6:50             29.67  2016-08-17    12:57
2 2016-07-28       1:30              8.17  2016-07-28    09:47

相关问题 更多 >