Pandas-将列中的秒添加到其他列中的datetime

2024-04-27 23:43:49 发布

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

我有一个包含两列的数据框,["StartDate" ,"duration"]StartDate列中的元素是datetime类型,duration是int。

比如:

StartDate  Duration
08:16:05    20  
07:16:01    20

我希望得到:

EndDate 
08:16:25
07:16:21

只需将秒数加到小时数。

我正在检查一些关于它的想法,比如delta time types,所有这些日期时间都有可能添加delta时间,但是到目前为止,我可以找到如何处理数据帧(以向量的方式,因为它可能迭代执行操作的所有行)。


Tags: 数据元素类型datetimetime时间inttypes
2条回答

考虑这个df

    StartDate   duration
0   01/01/2017  135
1   01/02/2017  235

你可以得到这样的日期时间列

df['EndDate'] = pd.to_datetime(df['StartDate']) + pd.to_timedelta(df['duration'], unit='s')
df.drop('StartDate,'duration', axis = 1, inplace = True)

你得到

    EndDate             
0   2017-01-01 00:02:15 
1   2017-01-02 00:03:55 

编辑:使用您发布的示例数据框架

df['EndDate'] = pd.to_timedelta(df['StartDate']) + pd.to_timedelta(df['Duration'], unit='s')
df.StartDate = df.apply(lambda x: pd.to_datetime(x.StartDate)+pd.Timedelta(Second(df.duration)) ,axis = 1)

相关问题 更多 >