美文网首页
Python获取上个月的第一天和最后一天

Python获取上个月的第一天和最后一天

作者: waketzheng | 来源:发表于2019-06-15 16:03 被阅读0次

    代码段:

    from datetime import date, timedelta
    today = date.today()
    last_day_of_last_month = d = date(today.year, today.month, 1) - timedelta(1)
    first_day_of_last_month = date(d.year, d.month, 1)
    

    实际代码中的函数:

    import calendar
    from datetime import date, timedelta
    
    DATE_FMT = "%Y-%m-%d"
    
    
    def month_day_pair(last_month=False):
        """获取字符串格式的本月初与本月底时间对(或上月初与上月底时间对)"""
        today = date.today()
        year, month = today.year, today.month
        if last_month:
            end = date(today.year, today.month, 1) - timedelta(1)
            start = date(end.year, end.month, 1)
        else:
            start = date(year, month, 1)
            _, last = calendar.monthrange(year, month)
            end = date(year, month, last)
        return f"{start:DATE_FMT}", f"{end:DATE_FMT}"
    

    相关文章

      网友评论

          本文标题:Python获取上个月的第一天和最后一天

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