给出一个时间戳,我想计算它周围的时间窗口。例如,如果时间是5月3日,我应该获得5月1日至5月31日的每月窗口。每天或每周都一样。
以下代码适用于每日和每月,如何编写每周窗口?
import datetime
# given a time, get the 1st and last times of its window
def get_timeslot(window,t):
if(window==1): # monthly window
t2 = t.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
if(t2.month==12):
m = 1
y = t2.year+1
else:
m = t2.month+1
y = t2.year
t3 = t2.replace(year=y,month=m) - datetime.timedelta(microseconds=1)
elif(window==2): # weekly window
pass
elif(window==3): # daily window
t2 = t.replace(hour=0, minute=0, second=0, microsecond=0)
t3 = t.replace(hour=23, minute=59, second=59, microsecond=999999)
else:
t2 = None
t3 = None
return t2,t3
t1 = datetime.datetime.utcnow()
print(t1, t1.year, t1.month, t1.day, t1.hour, t1.minute, t1.second, t1.microsecond, t1.tzinfo)
for i in range(14):
t2,t3 = get_timeslot(3, t1)
print(t2, '----',t3)
t1 = t3 + datetime.timedelta(microseconds=1)