美文网首页
Python日期解析

Python日期解析

作者: 7ming | 来源:发表于2019-05-23 00:30 被阅读0次

问题描述:
提供一个日期 (周日)---例 20190519 ,获取

    本周起止日期

    上周起止日期

    上月同周起止日期 (本周向前推4周)

    去年同期周起止日期 (按年计同周)

    月至今起止日期

    月至今上月同期

    月至今去年同期

解决:


import datetime

from dateutil.relativedelta import relativedelta

def parse_date(lastest_sunday):

    month_first_day=datetime.date(int(str(lastest_sunday)[0:4]),int(str(lastest_sunday)[4:6]),1)

    last_year_day=datetime.date(int(str(lastest_sunday)[0:4])-1,1,1)

    week_end=datetime.date(int(str(lastest_sunday)[0:4]),int(str(lastest_sunday)[4:6]),int(str(lastest_sunday)[6:8]))

    week_start=week_end-datetime.timedelta(days=6)

    last_week_start=week_start-datetime.timedelta(weeks=1)

    last_week_end=week_end-datetime.timedelta(weeks=1)

    lm_week_start=week_start-datetime.timedelta(weeks=4)

    lm_week_end=week_end-datetime.timedelta(weeks=4)

    mtd_start=month_first_day

    mtd_end=week_end

    lm_mtd_start=mtd_start- relativedelta(months=1)

    lm_mtd_end=mtd_end- relativedelta(months=1)

    ly_mtd_start=mtd_start- relativedelta(months=12)

    ly_mtd_end=mtd_end- relativedelta(months=12)

    week_num=week_start.isocalendar()[1]

    ly_week_num=1

    while int(last_year_day.year)==int(week_start.year)-1:

        if ly_week_num==week_num and last_year_day.weekday()+1==1:

            ly_week_start=last_year_day

            ly_week_end=ly_week_start+datetime.timedelta(days=6)

            break

        last_year_day=last_year_day+datetime.timedelta(days=1)

        ly_week_num=last_year_day.isocalendar()[1]



    config={

        'week_end':int(week_end.strftime('%Y%m%d')),

        'week_start':int(week_start.strftime('%Y%m%d')),

        'last_week_start':int(last_week_start.strftime('%Y%m%d')),

        'last_week_end':int(last_week_end.strftime('%Y%m%d')),

        'lm_week_start':int(lm_week_start.strftime('%Y%m%d')),

        'lm_week_end':int(lm_week_end.strftime('%Y%m%d')),

        'mtd_start':int(mtd_start.strftime('%Y%m%d')),

        'mtd_end':int(mtd_end.strftime('%Y%m%d')),

        'lm_mtd_start':int(lm_mtd_start.strftime('%Y%m%d')),

        'lm_mtd_end':int(lm_mtd_end.strftime('%Y%m%d')),

        'ly_mtd_start':int(ly_mtd_start.strftime('%Y%m%d')),

        'ly_mtd_end':int(ly_mtd_end.strftime('%Y%m%d')),

        'ly_week_start':int(ly_week_start.strftime('%Y%m%d')),

        'ly_week_end':int(ly_week_end.strftime('%Y%m%d'))

    }

    return config

相关文章

网友评论

      本文标题:Python日期解析

      本文链接:https://www.haomeiwen.com/subject/lzlmzqtx.html