python - 使用 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 分钟时,它应该输出正确的时间......
解决方案
您可以使用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
推荐阅读
- angularjs - Datepicker 使用格式 ''$filter('date')($scope.dt.datetime, 'd MMM, yyyy');' 时显示今天的日期 该怎么办?使用 Angular js 日期选择器
- amazon-web-services - AWS DynamoDB | 检查地图列表是否包含特定值
- r - 使用需要四个向量的函数在 R 中迭代
- gradle - 如果没有明确要求,Gradle 拒绝快照
- asp.net-core - 为什么推荐 Meta Packages 依赖 SDK 指定的隐式版本?
- arrays - 将 SAS 中的多个变量从 0/1 转换为“是”/“否”
- mysql - mysql 8.0.16 中用户定义的变量会存储在哪里?
- javascript - 如何创建带有浮动圆圈和内部文字的动画?
- java - 如何使用 java 模拟损坏的应用程序/八位字节流
- sql - 如何有效地提取仅包含 SQL 中具有重复元素的行的子表?