如何获取开始时间和结束时间范围之间的所有时间集?
我想在Python中获取开始时间和结束时间之间的所有时间,所以我使用带有范围函数的for循环。
有 2 个变量,a
和 b
,其时间格式为 %H:%M:%S
。
这两个变量是开始时间和结束时间,我想打印开始时间和结束时间之间的所有时间。
import datetime
from datetime import datetime
import time
a = '20:15:16'
b = '20:32:55'
a = datetime.strptime(a,'%H:%M:%S').time()
b = datetime.strptime(b,'%H:%M:%S').time()
for i in range(a,b):
print(i)
为此,我收到错误 - datetime.time' 对象无法解释为整数
。
我想打印 a
和 b
之间的所有时间。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
两次之间有无限的时刻。我认为您可能会问:“如何在A和B之间每秒或每一分钟打印一个时间戳?”
我认为您不想使用范围功能。您看到的错误是因为Range期望整数是输入,而不是整个DateTime对象。
这是可以做您想要的事情:
请注意,
我们只在需要时才提取时间零件,将对象作为DateTime对象进行轻松操作。
我使用此问题供参考:
什么是标准将n秒添加到DateTime.Time中的方法?
因此,这个问题真的很可爱。阅读有一些东西,“我需要在这两次之间打印“一直”,这给我带来了欢乐。
There are infinite moments between two times. I think you might be asking, "How can I print a timestamp for every second or every minute between A and B?"
I don't think you want to be using the range function. The error you are seeing is because range expects integers as input, not whole datetime objects.
Here is something that may do what you want:
Please notice the line,
where we only extract the time part when we need it, leaving the object as a datetime object for easy manipulation.
I used this question for reference:
What is the standard way to add N seconds to datetime.time in Python?
So this question is really adorable. There is something about reading, 'I need to print "all the time" between these two times' that gives me joy.