面朝大海,春暖华开

focus on scientific computue, 3dgis, spatial database
专注于科学计算、GIS空间分析

 

python 获取全年日期及日期详情

link: https://blog.csdn.net/qq_42711381/article/details/121118092

import datetime

"""
判断节假日采用chinese_calendar库,
支持 2004年 至 2022年,包括 2020年 的春节延长,
参考 https://pypi.org/project/chinesecalendar/#description。

也可以直接请求节假日数据接口
"""
from chinese_calendar import is_holiday

year = 2021


# 得到一年中所有的日期
def get_whole_year(year=year):
    begin = datetime.date(year, 1, 1)
    now = begin
    end = datetime.date(year, 12, 31)
    delta = datetime.timedelta(days=1)
    days = []
    while now <= end:
        days.append(now.strftime("%Y-%m-%d"))
        now += delta
    return days


# 获取季度
def get_quarter(month):
    # 第几季度
    if 1 <= month <= 3:
        return 1
    elif 4 <= month <= 6:
        return 2
    elif 7 <= month <= 9:
        return 3
    else:
        return 4


# 判断是否为周末
def is_weekends(weekday):
    return False if 1 <= weekday <= 5 else True


# 得到日期的具体信息
def get_details(day):
    #
    year = day.strftime("%Y")
    #
    month = day.strftime("%m")
    # 周几
    wk = int(day.strftime("%w"))
    weekday = 7 if wk == 0 else wk
    # 一年中的第几天
    day_of_year = day.strftime("%j")
    # 一年中的第几周
    week_of_year = int(day.strftime("%W")) + 1
    # 季度
    quarter = get_quarter(int(month))
    # 是否为周末
    is_weekend = is_weekends(int(weekday))
    # 是否为节假日
    is_holi = is_holiday(day)
    return [year, month, weekday, day_of_year, week_of_year, quarter, is_weekend, is_holi]


for year in [2021, 2022]:
    days = get_whole_year(year)
    for day in days:
        detail = get_details(day)

 

posted on 2022-05-29 18:27  风过 无痕  阅读(388)  评论(0编辑  收藏  举报

导航

向日葵支付宝收钱码