【问题标题】:Split Time range into multiple time periods based on interval in Python根据Python中的间隔将时间范围拆分为多个时间段
【发布时间】:2020-09-03 07:12:40
【问题描述】:

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

例如,时间范围为 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
]

【问题讨论】:

    标签: python python-3.x time


    【解决方案1】:

    您可以通过添加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']
    

    【讨论】:

    • 除了datetime.timedelta(0, 60) * 30 你也可以datetime.timedelta(minutes=30)
    【解决方案2】:

    使用pandas.date_range

    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']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-19
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      • 2018-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多