需求背景:数据当周出不完装的情况下,都会去取上周数据,也就是完全不在更新的数据(适用于间隔时间段的数据)
例如:当天数是2021-11-04 我们会去取2021-10-24(上上周六) 至2021-10-30(上周日) 之间的数据,
在本周,也就是 2021-11-01至2021-11-07(一周七天) ,不管任何一天都要取2021-10-24(上上周六) 至2021-10-30(上周日) 之间的数据。
1.当天日期我们根据datetime模块来取
import datetime
datetime.datetime.today()
2.当天日期和我们要得到的日期之间的差值 我们使用timedelta模块
from datetime import timedelta
3.综合代码如下:
# -*- coding: utf-8 -*-
import datetime
from datetime import timedelta
#根据当前日期获取 上上周日 到 上周六 的日期值
class ActiveLastWeek:
def __init__(self):
pass
def get_week_day(self,date_s):
week_day_dict = {
0 : '1',
1 : '2',
2 : '3',
3 : '4',
4 : '5',
5 : '6',
6 : '7',
}
day = date_s.weekday()
return week_day_dict[day]
def active_date(self,choice_date):
last_last_sunday = ''
last_saturday = ''
# choice_date = datetime.datetime.today()
week = self.get_week_day(choice_date)
if week == '1':
print('周一')
last_saturday = choice_date - timedelta(days=2)
last_last_sunday = choice_date - timedelta(days=8)
if week == '2':
print('周二')
last_saturday = choice_date - timedelta(days=3)
last_last_sunday = choice_date - timedelta(days=9)
elif week == '3':
print('周三')
last_saturday = choice_date - timedelta(days=4)
last_last_sunday = choice_date - timedelta(days=10)
elif week == '4':
print('周四')
last_saturday = choice_date - timedelta(days=5)
last_last_sunday = choice_date - timedelta(days=11)
elif week == '5':
print('周五')
last_saturday = choice_date - timedelta(days=6)
last_last_sunday = choice_date - timedelta(days=12)
elif week == '6':
print('周六')
last_saturday = choice_date - timedelta(days=7)
last_last_sunday = choice_date - timedelta(days=13)
elif week == '7':
print('周日')
last_saturday = choice_date - timedelta(days=8)
last_last_sunday = choice_date - timedelta(days=14)
now_date = choice_date.date()
from_date = last_last_sunday.date()
to_date = last_saturday.date()
# print(now_date,from_date,to_date)
print('当天:{0}'.format(now_date))
print('上上周六:{0}'.format(from_date))
print('上周日:{0}'.format(to_date))
if __name__ == '__main__':
t = ActiveLastWeek()
t.active_date(datetime.datetime.today())
4.运行结果如下