Python实现按间隔批量更新范围内元素的小时区间问题
Fix for Hour Interval Grouping Issue
Corrected Code
from datetime import datetime utc_time = datetime.utcnow() utc_hour = utc_time.hour minute = [] hour = [] day = [] month = [] week = [] _hour = utc_hour count = 0 elements_per_group = 3 total_elements = 12 layer = 'get' # Define the missing variable while count < total_elements: if layer == 'get': minute.append('0-59') # Shift the hour interval every time we start a new group if count != 0 and count % elements_per_group == 0: _hour += 4 end_hour = _hour + 4 hour_interval = f"{_hour}-{end_hour}" hour.append(hour_interval) print(count, elements_per_group, hour) count += 1
What Was Wrong & How We Fixed It
- Missing Variables: The original code used
layerandxwithout defining them—this would throw aNameError. We addedlayer = 'get'and removed the undefinedxfrom the print statement. - No Interval Progression: The
_hourvariable was never updated, so every element got the same starting interval. We added logic to increment_hourby 4 each time we start a new group (after every 3 elements). - Extra Element: The loop ran
count <= 12, which creates 13 elements instead of 12. Changing it tocount < 12fixes this. - Redundant Code: The line
a = [hour.append(gen_hour)]was unnecessary—hour.append()modifies the list directly, and wrapping it in a list just creates a list with aNonevalue. We removed this line.
Example Result (UTC Hour = 6)
The hour list will now correctly group intervals:
['6-10', '6-10', '6-10', '10-14', '10-14', '10-14', '14-18', '14-18', '14-18', '18-22', '18-22', '18-22']
内容的提问来源于stack exchange,提问作者devi
相关产品推荐
相关产品推荐

