python - 按日期和时间迭代 - 半小时

时间:2016-06-08 23:30:47

标签: python datetime

我考虑如何按以下方式按数据和时间进行迭代:

2016-06-10,00:00
2016-06-10,01:30
2016-06-10,02:00
2016-06-10,02:30
....

有人能帮助我吗?

2 个答案:

答案 0 :(得分:2)

import datetime
from datetime import timedelta

format = "%Y-%m-%d,%H:%M"

start = datetime.datetime(2016, 6, 10, 0, 0)

minutes = 0

for i in range(6):
    print (start + timedelta(minutes=minutes)).strftime(format)
    minutes += 30

输出:

$ python timespan.py  
2016-06-10,00:00  
2016-06-10,00:30  
2016-06-10,01:00  
2016-06-10,01:30  
2016-06-10,02:00  
2016-06-10,02:30  

答案 1 :(得分:1)

使用timedelta生成一系列datetime个对象:

from datetime import timedelta, datetime

start_date = datetime(2016, 6, 9, 5, 0, 0)
for td in (start_date + timedelta(minutes=30*it) for it in xrange(10)):
    print td.strftime("%Y-%m-%d,%H:%M")

输出:

2016-06-09,05:00
2016-06-09,05:30
2016-06-09,06:00
2016-06-09,06:30
2016-06-09,07:00
2016-06-09,07:30
2016-06-09,08:00
2016-06-09,08:30
2016-06-09,09:00
2016-06-09,09:30