如何获得一个时间范围内的所有时间

问题描述

使用python,我希望获得一个范围内(24小时制)的所有时间。我该怎么做?

如果

start="10:00"
end="10:05"

那我想得到

["10:00","10:01","10:02","10:03","10:04","10:05"]

解决方法

使用日期时间模块可能会有用。如果您要使用军事时间,这是我为您解决的问题的想法:

import datetime

start = datetime.time(10,0) # 10:00
end = datetime.time(10,5) # 10:05
TIME_FORMAT = "%H:%M" # Format for hours and minutes
times = [] # List of times 
while start <= end:
    times.append(start)
    if start.minute == 59: # Changes the hour at the top of the hour and set the minutes back to 0
        start = start.replace(minute=0) # have to use the replace method for changing the object
        start = start.replace(hour=start.hour + 1)
    else:
        start = start.replace(minute=start.minute + 1)
times = [x.strftime(TIME_FORMAT) for x in times] # Uses list comprehension to format the objects
print(times)