1. 程式人生 > >根據指定日期獲取上一週和上上一週的所有日期

根據指定日期獲取上一週和上上一週的所有日期

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']