在Python中,根据时间间隔将时间范围拆分为多个时间段



我有一个时间范围和一个间隔,我需要根据间隔值将时间范围划分为多个时间段。

例如,时间范围是9:30到11:30,间隔是30,输出时间段应该作为日期时间对象在列表中

输出:

[
2020-08-24 9:30 - 2020-08-24 10:00,
2020-08-24 10:00 - 2020-08-24 10:30 
2020-08-24 10:30 - 2020-08-24 11:00, 
2020-08-24 11:00 - 2020-08-24 11:30
]

您可以通过添加timedelta对象来对datetime对象执行算术运算。

如果每个周期的间隔不是总数的精确除数,那么您可能需要确切地决定需要什么行为,但在这种情况下,本例将给出最后一个短周期。

import datetime
tstart = datetime.datetime(2020,8,24,9,30)
tend = datetime.datetime(2020,8,24,11,30)
interval = datetime.timedelta(minutes=30)
periods = []
period_start = tstart
while period_start < tend:
period_end = min(period_start + interval, tend)
periods.append((period_start, period_end))
period_start = period_end
print(periods)

这给出了(插入换行符以便于阅读(:

[(datetime.datetime(2020, 8, 24, 9, 30), datetime.datetime(2020, 8, 24, 10, 0)),
(datetime.datetime(2020, 8, 24, 10, 0), datetime.datetime(2020, 8, 24, 10, 30)),
(datetime.datetime(2020, 8, 24, 10, 30), datetime.datetime(2020, 8, 24, 11, 0)),
(datetime.datetime(2020, 8, 24, 11, 0), datetime.datetime(2020, 8, 24, 11, 30))]

对于您想要的字符串输出格式,您可以这样做:

def format_time(dt):
return dt.strftime("%Y-%m-%d %H:%M")
print(['{} - {}'.format(format_time(start), format_time(end))
for start, end in periods])

给予:

['2020-08-24 09:30 - 2020-08-24 10:00',
'2020-08-24 10:00 - 2020-08-24 10:30',
'2020-08-24 10:30 - 2020-08-24 11:00',
'2020-08-24 11:00 - 2020-08-24 11:30']

使用pandas.date_range

import pandas as pd
bins = pd.date_range(start='2020-08-24 9:30', end='2020-08-24 11:30', freq='30min').astype(str)
res = [' - '.join(x) for x in zip(bins[: -1], bins[1: ])]
print(res)

输出:

['2020-08-24 09:30:00 - 2020-08-24 10:00:00',
'2020-08-24 10:00:00 - 2020-08-24 10:30:00',
'2020-08-24 10:30:00 - 2020-08-24 11:00:00',
'2020-08-24 11:00:00 - 2020-08-24 11:30:00']