gpt4 book ai didi

python - 如何计算pandas中的时间差

转载 作者:行者123 更新时间:2023-12-01 07:09:55 24 4
gpt4 key购买 nike

我在 pandas 中有以下数据框

 code     srt_date       srt_time      end_time    fina_datetime
123 2019-01-01 23:23:00 00:12:00 2019-01-02 00:13:00
123 2019-01-02 00:13:00 00:14:00 2019-01-02 00:15:00
123 2019-01-02 23:00:00 00:15:00 2019-01-03 00:16:00

我想计算 fina_datetime - end_time 我正在 pandas 中做以下事情

 df['end_time'] = df['srt_date'].map(str) +" "+ df['end_time'].map(str)
df['end_time'] = pd.to_datetime(df['end_time'], format = "%Y-%m-%d %H:%M:%S")
df['latency_in_secs'] = [x-y for x, y in zip(df['final_datetime'] , df['end_time'])]
df['latency_in_secs'] = df.latency_in_secs.dt.total_seconds()

当日期进入下一个日期时,上述代码会出现问题,例如第一排和第三排。我该如何在 Pandas 中做到这一点?

我想要的数据框是

 code     srt_date       srt_time      end_time    fina_datetime        latency_in_secs 
123 2019-01-01 23:23:00 00:12:00 2019-01-02 00:13:00 60
123 2019-01-02 00:13:00 00:14:00 2019-01-02 00:15:00 60
123 2019-01-02 23:00:00 00.15:00 2019-01-03 00:16:00 60

最佳答案

IIUC,您可以屏蔽end_time < srt_time的位置并将日期加一:

# convert to timedelta
df['srt_time'] = pd.to_timedelta(df['srt_time'])
df['end_time'] = pd.to_timedelta(df['end_time'])

# convert to datetime
df['srt_date'] = pd.to_datetime(df['srt_date'])
df['fina_datetime'] = pd.to_datetime(df['fina_datetime'])

# the normal end
end_dates = df['srt_date'] + df['end_time']

# increase the end time with end_time < srt_time by one day
end_dates.loc[df['end_time'].le(df['srt_time'])] += pd.to_timedelta(1, unit='D')

# substract:
df['latency_in_secs'] = (df['fina_datetime'].sub(end_dates)
.dt.total_seconds()
)

输出:

   code   srt_date srt_time end_time       fina_datetime  latency_in_secs
0 123 2019-01-01 23:23:00 00:12:00 2019-01-02 00:13:00 60.0
1 123 2019-01-02 00:13:00 00:14:00 2019-01-02 00:15:00 60.0
2 123 2019-01-02 23:00:00 00:15:00 2019-01-03 00:16:00 60.0

关于python - 如何计算pandas中的时间差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58275510/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com