当前位置: 首页 > article >正文

【Python】工作笔记:返回当月第一天、昨天;上月第一天、当天;全年节假日

目录

  • 专栏导读
  • 1、背景介绍
  • 2、库的安装
  • 代码1:当月第一天、昨天
  • 代码2:上月第一天、当天
  • 代码3:上月第一天、明天
  • 代码4:检查某天是否是法定节假日
  • 代码5:获取2025年所有法定节假日
  • 总结

专栏导读

  • 🌸 欢迎来到Python办公自动化专栏—Python处理办公问题,解放您的双手

  • 🏳️‍🌈 博客主页:请点击——> 一晌小贪欢的博客主页求关注

  • 👍 该系列文章专栏:请点击——>Python办公自动化专栏求订阅

  • 🕷 此外还有爬虫专栏:请点击——>Python爬虫基础专栏求订阅

  • 📕 此外还有python基础专栏:请点击——>Python基础学习专栏求订阅

  • 文章作者技术和水平有限,如果文中出现错误,希望大家能指正🙏

  • ❤️ 欢迎各位佬关注! ❤️

1、背景介绍

  • 我们在日常办公中,经常会需要获取当前月份的第一天、昨天;

  • 我们在日常办公中,经常会需要获取上个月份的第一天、当天;

2、库的安装

用途安装
datetime处理日期内置库无需安装
datetime处理日期pip install chinesecalendar

代码1:当月第一天、昨天

# -*- coding: UTF-8 -*-
'''
@Project :8组-邹佩佩-差异线上化 
@File    :测试.py
@IDE     :PyCharm 
@Author  :庄志权(18721945973)
@Date    :2025/3/27 15:05 
'''

import datetime


def get_first_last_day_of_month():
    # 获取当前日期
    now = datetime.datetime.now()

    # 获取当前月份的第一天
    first_day_of_month = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)

    # 获取当天的前一天(昨天)
    last_day = now - datetime.timedelta(days=1)
    last_day = last_day.replace(hour=23, minute=59, second=59, microsecond=0)

    # 输出结果
    # print(f'当前日期: {now.strftime("%Y-%m-%d")}')
    print(f'本月第一天: {first_day_of_month.strftime("%Y-%m-%d")}')
    print(f'前一天: {last_day.strftime("%Y-%m-%d")}')

    first_day_of_month = first_day_of_month.strftime("%Y-%m-%d")
    last_day = last_day.strftime("%Y-%m-%d")

    return first_day_of_month, last_day


get_first_last_day_of_month()

代码2:上月第一天、当天

from datetime import datetime, date, timedelta

def get_last_month_dates():
    # 获取当前日期
    today = date.today()
    
    # 计算上个月的第一天
    if today.month == 1:
        last_month_first_day = date(today.year - 1, 12, 1)
    else:
        last_month_first_day = date(today.year, today.month - 1, 1)
    
    # 格式化日期为YYYY-MM-DD
    last_month_first_day_str = last_month_first_day.strftime("%Y-%m-%d")
    today_str = today.strftime("%Y-%m-%d")
    
    return last_month_first_day_str, today_str

# 示例用法
last_month_first, current_day = get_last_month_dates()
print(f"上月第一天: {last_month_first}, 当天: {current_day}")

代码3:上月第一天、明天

import calendar
from datetime import date, timedelta

def get_last_month_and_tomorrow():
    today = date.today()
    tomorrow = today + timedelta(days=1)
    
    # 计算上个月的第一天
    year = today.year - (1 if today.month == 1 else 0)
    month = 12 if today.month == 1 else today.month - 1
    last_month_first_day = date(year, month, 1)
    
    return last_month_first_day.strftime("%Y-%m-%d"), tomorrow.strftime("%Y-%m-%d")

# 示例调用
print(get_last_month_and_tomorrow())

代码4:检查某天是否是法定节假日

pip install chinesecalendar
import chinesecalendar as calendar
from datetime import date

# 检查日期是否节假日(包含调休的工作日)
day = date(2025, 10, 1)  # 2025年国庆节
is_holiday = calendar.is_holiday(day)
print(f"{day} 是节假日吗? {is_holiday}")  # 输出: True

# 检查某天是否工作日(考虑调休)
is_workday = calendar.is_workday(day)
print(f"{day} 是工作日吗? {is_workday}")  # 输出: False

代码5:获取2025年所有法定节假日

pip install chinesecalendar
from datetime import date, timedelta

def get_holidays(year):
    holidays = []
    current = date(year, 1, 1)
    end = date(year, 12, 31)
    
    while current <= end:
        if calendar.is_holiday(current):
            # 获取节假日名称(通过遍历匹配)
            for name, dates in calendar.get_holiday_detail(current):
                holidays.append((current, name))
                break  # 只需第一个匹配名称
        current += timedelta(days=1)
    
    return holidays

# 示例:打印2025年所有节假日
holidays_2025 = get_holidays(2025)
for day, name in holidays_2025:
    print(f"{day.strftime('%Y-%m-%d')}: {name}")

总结

  • 希望对初学者有帮助

  • 致力于办公自动化的小小程序员一枚

  • 希望能得到大家的【一个免费关注】!感谢

  • 求个 🤞 关注 🤞

  • 此外还有办公自动化专栏,欢迎大家订阅:Python办公自动化专栏

  • 求个 ❤️ 喜欢 ❤️

  • 此外还有爬虫专栏,欢迎大家订阅:Python爬虫基础专栏

  • 求个 👍 收藏 👍

  • 此外还有Python基础专栏,欢迎大家订阅:Python基础学习专栏


http://www.kler.cn/a/613105.html

相关文章:

  • 如何在 Postman 中正确设置 Session 以维持用户状态?
  • 详解Http:在QT中使用Http协议
  • Android 屏蔽某应用的ANR弹窗
  • 淘宝flexible.js+rem适配移动端
  • Pydantic字段元数据指南:从基础到企业级文档增强
  • Github 热点项目 awesome-mcp-servers MCP 服务器合集,3分钟实现AI模型自由操控万物!
  • SEO(搜索引擎优化)详解
  • Flask(六)数据库与模型操作
  • Linux内核2-TFTP与NFS环境搭建
  • VSCode:Linux下安装使用
  • NX二次开发刻字功能——预览功能
  • 微信小程序——解构赋值与普通赋值
  • 【PostgreSQL内核学习 —— (sort算子)】
  • 数据库同步中间件PanguSync:如何跳过初始数据直接进行增量同步
  • HCIP VRRP MSTP 交换综合实验
  • 5.Matplotlib:高级绘图
  • SvelteKit 最新中文文档教程(13)—— Hooks
  • RHCA核心课程技术解析4:红帽服务管理与自动化深度实践
  • Java EE 进阶:MyBatis案例练习
  • 有价值的面试问题