Python:创建包含时间的数组并能够对它们求和

Python: create arrays containing times and be able to sum them

我需要创建包含时间值 (hh:mm:ss) 的数组,从每个数组中采样一个值并将它们相加。 我使用 pd.timedelta_range() 创建数组并使用 rd.choices() 进行采样。 我需要将采样的出发时间和持续时间相加以获得到达时间,但出发时间 + 持续时间只是打印出这两个值而不提供总数。

departure_time = pd.timedelta_range('04:00:00', '09:45:00', freq='15T')
departure_prob = (0.008, 0.008, 0.008,  0.008,  0.032,  0.032, 0.032,   0.032,  0.082,  0.082, 0.082,    
0.082,  0.08,   0.08, 0.08, 0.08,   0.034,  0.034,  0.034,  0.034,  0.014,  0.014, 0.014,   0.014)

duration_time = pd.timedelta_range('00:15:00', '01:15:00', freq='15T')
duration_prob = (0.355, 0.321, 0.152, 0.086, 0.086)

departure = rd.choices(departure_time, departure_prob)
duration = rd.choices(duration_time, duration_prob)
print(departure+duration)

有办法吗?

试试这个

import pandas as pd
import random as rd
import datetime

#departure_time = pd.timedelta_range('04:00:00', '09:45:00', freq='15T')
departure_time = pd.date_range(start='2017-01-01 10:00', end='2017-01-02 09:00', freq='1h')
departure_prob = (0.008, 0.008, 0.008,  0.008,  0.032,  0.032, 0.032,   0.032,  0.082,  0.082, 0.082,    
0.082,  0.08,   0.08, 0.08, 0.08,   0.034,  0.034,  0.034,  0.034,  0.014,  0.014, 0.014,   0.014)

duration_time = pd.timedelta_range('00:15:00', '01:15:00', freq='15T')
duration_prob = (0.355, 0.321, 0.152, 0.086, 0.086)

departure = rd.choices(departure_time, departure_prob)
duration = rd.choices(duration_time, duration_prob)

print(departure[0]+duration[0])

如果你想得到一个时间,你必须使用一个日期。 Timedelta,顾名思义,就是一个时间段。

您遇到的问题是变量 department 和 duration 是列表(每个列表包含一个元素)。 您需要提取 timedelta 对象: departure[0]+duration[0]

或更清楚:

departure = rd.choices(departure_time, departure_prob)[0]
duration = rd.choices(duration_time, duration_prob)[0]

那么 departure + duration 将按照您的预期工作。

干杯!