gpt4 book ai didi

python - 将时间戳添加到分钟

转载 作者:行者123 更新时间:2023-12-01 00:56:47 26 4
gpt4 key购买 nike

我有一个包含 200 行的 DataFrame df。前几行如下所示:

+--------------+----------+----------------+
|Customer name | Arrival | Actual Arrival |
+--------------+----------+----------------+
| Customer 21 | 20 | |
| Customer 22 | 30 | |
| Customer 23 | 20 | |
| Customer 24 | 10 | |
| Customer 25 | 20 | |
+--------------+----------+----------------+

到达列显示从开始时间算起的到达时间分钟。因此,我想通过向到达列值添加固定时间戳(开始时间)来创建实际到达列。例如:如果开始时间是 07:00;

+--------------+----------+----------------+
|Customer name | Arrival | Actual Arrival |
+--------------+----------+----------------+
| Customer 21 | 20 | 07:20 |
| Customer 22 | 30 | 07:30 |
| Customer 23 | 20 | 07:20 |
| Customer 24 | 10 | 07:10 |
| Customer 25 | 60 | 08:00 |
+--------------+----------+----------------+

如何在 python 中执行此操作?

最佳答案

您可以尝试以下操作吗:

import datetime
actual_start_time = datetime.time(7, 0)
start_time = datetime.datetime.combine(datetime.datetime.today().date(), actual_start_time)
df['Actual Arrival'] = df['Arrival'].apply(lambda x: start_time + datetime.timedelta(minutes=x))

示例:

>>> df = pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]]).T
>>> df.columns = ['name', 'Arrival']
>>> df
name Arrival
0 1 5
1 2 6
2 3 7
3 4 8
>>> start_time = datetime.datetime.strptime('2019-05-17 7:0:0', '%Y-%m-%d %H:%M:%S')
>>> df['Actual Arrival'] = df['Arrival'].apply(lambda x: start_time + datetime.timedelta(minutes=x))
>>> df
name Arrival Actual Arrival
0 1 5 2019-05-17 07:05:00
1 2 6 2019-05-17 07:06:00
2 3 7 2019-05-17 07:07:00
3 4 8 2019-05-17 07:08:00

如果您只想要时间,可以执行以下操作:

>>> df['Actual Arrival'] = df['Arrival'].apply(lambda x: (start_time + datetime.timedelta(minutes=x)).time())
>>> df
name Arrival Actual Arrival
0 1 5 07:05:00
1 2 6 07:06:00
2 3 7 07:07:00
3 4 8 07:08:00

关于python - 将时间戳添加到分钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56179983/

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