根据指定日期获取上一周和上上一周的所有日期

import math
import calendar
import datetime
from datetime import date
from dateutil.rrule import rrule, DAILY


def get_week_day(data):
    y = int(data[:4])  # 2018
    m = int(data[4:6])  # 08
    d = int(data[-2:])  # 31

    if str(m).startswith('0'):
        m = m[-1:]
    the_date = datetime.datetime(y, m, d)

    data_dict = {1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 0: "7"}
    if m == 1:
        m = 13
        y = y - 1
    elif m == 2:
        m = 14
        y = y - 1
    all_day = math.floor(
        (y - 1) + (y - 1) / 4 - (y - 1) / 100 + (y - 1) / 400 + 13 * (m + 1) / 5 + (m - 1) * 28 - 7 + d)
    x = all_day % 7
    week_how = data_dict.get(x)

    result_date1 = the_date + datetime.timedelta(days=-int(week_how) - 6)
    last_monday = result_date1.strftime('%Y%m%d')  # 上一周的星期一

    result_date7 = the_date + datetime.timedelta(days=-int(week_how))
    last_sunday = result_date7.strftime('%Y%m%d')  # 上一周的星期日

    st_year = int(last_monday[0:4])  # 2018
    st_mon = int(last_monday[4:6])  # 11
    st_day = int(last_monday[-2:])  # 05

    en_year = int(last_sunday[0:4])  # 2018
    en_mon = int(last_sunday[4:6])  # 11
    en_day = int(last_sunday[-2:])  # 11

    last_week_list = []
    last_last_week_list = []

    time_start = date(st_year, st_mon, st_day)
    time_end = date(en_year, en_mon, en_day)
    for dt in rrule(DAILY, dtstart=time_start, until=time_end):
        last_week_list.append(dt.strftime("%Y%m%d"))

    result_date01 = the_date + datetime.timedelta(days=-int(week_how) - 13)
    last_monday_of_last_week = result_date01.strftime('%Y%m%d')  # 上上一周的星期一

    result_date_07 = the_date + datetime.timedelta(days=-int(week_how) - 7)
    last_sunday_of_last_week = result_date_07.strftime('%Y%m%d')  # 上上一周的星期日

    s_st_year = int(last_monday_of_last_week[0:4])
    s_st_mon = int(last_monday_of_last_week[4:6])
    s_st_day = int(last_monday_of_last_week[-2:])

    e_en_year = int(last_sunday_of_last_week[0:4])
    e_en_mon = int(last_sunday_of_last_week[4:6])
    e_en_day = int(last_sunday_of_last_week[-2:])

    time_start = date(s_st_year, s_st_mon, s_st_day)
    time_end = date(e_en_year, e_en_mon, e_en_day)

    for dt in rrule(DAILY, dtstart=time_start, until=time_end):
        last_last_week_list.append(dt.strftime("%Y%m%d"))

    print(last_week_list, last_last_week_list)

    return last_week_list, last_last_week_list


get_week_day("20181018")

结果:

​
['20181008', '20181009', '20181010', '20181011', '20181012', '20181013', '20181014'] 
['20181001', '20181002', '20181003', '20181004', '20181005', '20181006', '20181007']

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值