获取当前月的第一天和最后一天,上一个月的第一天和最后一天

该博客分享了一段Python代码,用于获取上一个月的第一天和最后一天的日期。通过datetime和calendar模块,实现了对当前日期的计算,得到所需月份的日期范围,并打印展示。这段代码可应用于数据分析或日志记录等场景中处理时间范围的问题。
摘要由CSDN通过智能技术生成

运用到的点,觉得写的还行,就分享一下

import datetime
import calendar


def get_date():
    """
    获取上月第一天和最后一天并返回 (元组)
    example:
    now date:2020-10-12
    return:2020-09-01,2020-09-30
    """
    today = datetime.date.today()  # 当前日期

    last_day_last_month = datetime.date(today.year, today.month, 1) - datetime.timedelta(1)  # 上个月最后一天
    first_day_last_month = datetime.date(last_day_last_month.year, last_day_last_month.month, 1)  # 上个月第一天

    first_day_month = datetime.date(today.year, today.month, 1)  # 这个月第一天
    days_nums = calendar.monthrange(today.year, today.month)[1]  # 获取一个月有多少天

    last_day_month = first_day_month + datetime.timedelta(days=days_nums - 1)  # 这个月最后一天

    print("上个月第一天:{}\n上个月最后一天:{}\n这个月第一天:{}\n这个月最后一天:{}\n"
          .format(first_day_last_month, last_day_last_month, first_day_month, last_day_month))

    return first_day_last_month, last_day_last_month

运行结果如下
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值