我正在尝试提出一种方法来生成一组时间戳,每小时15分钟,上个月每天8小时。我的方法是自上而下,首先生成日期,然后使用这些候选项每天生成8个子时间戳,然后最终生成每小时4个孙子时间戳。
collection = []
numdays = 10
numHours = 4
numMinutes = 5
base = datetime.datetime.today()
datelist = [base - datetime.timedelta(days=x) for x in range(0, numdays)]
hourList = [date - datetime.timedelta(hours=x) for date in datelist]
minuteList = [hour - datetime.timedelta(minutes=numMinutes) for hour in hourList]
有没有更优雅的子结构来考虑这个?
答案 0 :(得分:1)
这样的事情怎么样:
first = datetime(2016, 8, 1, 8, 0, 0)
dates = [first]
for days in range(1, 31): # How many days.
for _ in range(8 * 4): # 8 hours, 4x 15 min intervals per hour
dates.append(dates[-1] + timedelta(minutes = 15))
dates.append(dates[0] + timedelta(days = days))
答案 1 :(得分:0)
要生成具有固定增量的日期时间列表,请执行以下操作(生成长度为8 * 4且间隔为15分钟的列表的示例,其中涉及问题的一部分):
`
from datetime import datetime, timedelta
first = datetime(2016, 8, 1, 8, 0, 0)
delta = timedelta(minutes = 15)
dates = (first + delta * x for x in range(8 * 4))
`
dates
是一个生成器对象。要使用print(list(dates))