【问题标题】:How to get all times within a time range [duplicate]如何获取时间范围内的所有时间[重复]
【发布时间】:2020-12-01 13:05:58
【问题描述】:

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

如果

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

那我想得到

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

【问题讨论】:

  • 如果时间是在两个不同的日子里怎么办?
  • 你试过什么?你在使用datetime 模块吗? datetime.timedelta(minutes=1) 对此很有用。
  • 这能回答你的问题吗? Creating a range of dates in Python

标签: python datetime time


【解决方案1】:

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

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-30
    • 1970-01-01
    相关资源
    最近更新 更多