如何创建每天增加15分钟的时间列表?

时间:2018-10-06 23:44:44

标签: python datetime time

在python中,我想创建一个时间列表(例如[00:15:00, 00:30:00, ... , 23:30:00, 23:45:00]),尽管我可以用日期来完成此操作,但我不知道如何只用时间来做到这一点。

3 个答案:

答案 0 :(得分:1)

很难说出需要什么作为结果列表,但是如果您只想要字符串,请考虑以下内容:

spacing = 15    # in minutes
lst = [str(i*datetime.timedelta(minutes=spacing)) for i in range(24*60//spacing)]
print(lst)

注意:这假设(并要求)一天中的分钟数可以被spacing整除,否则您将获得一个接近但不正确的列表。

输出:

['0:00:00', '0:15:00', '0:30:00', '0:45:00', '1:00:00', '1:15:00', '1:30:00', 
 '1:45:00', '2:00:00', '2:15:00', '2:30:00', '2:45:00', '3:00:00', '3:15:00', 
 '3:30:00', '3:45:00', '4:00:00', '4:15:00', '4:30:00', '4:45:00', '5:00:00', 
 '5:15:00', '5:30:00', '5:45:00', '6:00:00', '6:15:00', '6:30:00', '6:45:00', 
 ...
 '21:00:00', '21:15:00', '21:30:00', '21:45:00', '22:00:00', '22:15:00', 
 '22:30:00', '22:45:00', '23:00:00', '23:15:00', '23:30:00', '23:45:00']

答案 1 :(得分:0)

您可以创建一系列整数值,每个整数值都是从一天开始算起的秒数。

def list_of_times(interval_in_seconds):
    return range(0, 86400, interval_in_seconds)

然后您可以将其除以60或使用Timedelta对象进行格式化来将其调整为分钟。

import datetime
datetime.timedelta(seconds=your_value_in_seconds)

可以随意设置Timedelta对象的格式

答案 2 :(得分:0)

此代码创建并打印您要求的列表:

out = []
for x in [str(x) for x in range(24)]:
    x = "0" + x if len(x) == 1 else x
    for i in [str(x) for x in range(60)][::15]:
        i = "0" + i if len(i) == 1 else i
        out.append("{}:{}:00".format(x, i))
print(out)

这有点笨重,但却是一种无需进口的方式。