可能嵌套循环

时间:2020-07-03 15:41:07

标签: python

start_month = 10
start_day = 24
end_month = 11
end_day = 28


time_stamp = []
for r in range(0,24):
    if 0 <=r <= 9:
        hr_str = '0' + str(r) + ':'
        time_stamp.append(hr_str)
    else:
        hr_str = str(r)+ ':'
        time_stamp.append(hr_str)

我需要遍历并制作一个可能每个月,一天和一个小时的列表。如上所述,我已经计算出小时,但是我不确定如何获取月份和日期。

1 个答案:

答案 0 :(得分:0)

在一段时间内,您将需要datetime函数。这是一种可行的方法:

import datetime

start_month = 12
start_day = 24
end_month = 1
end_day = 28

start = datetime.datetime(2019, start_month, start_day)  # <- 2019 specified
end = datetime.datetime(2020, end_month, end_day)        # <- 2020 specified

lst = [(start + datetime.timedelta(hours=h)).strftime('%m-%d %H') for h in range((end-start).days * 24)]

for datehour in lst:
    print(datehour)