首页 > 解决方案 > 使用 for 循环打印时间序列

问题描述

我想创建一个打印的循环:

"The train will leave at 13:36"
"The train will leave at 13:56"
"The train will leave at 14:16"
"The train will leave at 14:36"
"The train will leave at 14:56"
"The train will leave at 15:16"
etc. etc...

我有一个代码说:

h = 13 
m = 36

for i in range(5):
    print("The train will leave at {}:{} ".format(h,m))
    m = m + 20

    if 60 <= m:
        break
    print("The train will leave at {}:{} ".format(h,m))
    h = h+1
    m = m-60+20

输出是:

The train will leave at 13:36 
The train will leave at 13:56 
The train will leave at 14:16 
The train will leave at 14:36 
The train will leave at 15:-4 
The train will leave at 15:16 
The train will leave at 16:-24 
The train will leave at 16:-4
The train will leave at 17:-44
The train will leave at 17:-24

我该如何解决它,所以分钟增量为 20 分钟,每次达到 60 分钟时,它应该输出正确的时间......

标签: pythonpython-3.xfor-loop

解决方案


您可以使用datetime标准库中的模块:

from datetime import timedelta, datetime

t = datetime(hour=13, minute=36, year=2019, month=6, day=9)

for i in range(5):
    print("The train will leave at {}:{} ".format(t.hour,t.minute))
    t += timedelta(minutes=20)

印刷:

The train will leave at 13:36 
The train will leave at 13:56 
The train will leave at 14:16 
The train will leave at 14:36 
The train will leave at 14:56 

推荐阅读