Python小技 打印月初月末

使用datetime模块打印月初与月末

#!usr/bin/env python3
# -*- coding: UTF-8 -*-
# !@Time:2020/9/9 10:22
# !@Author:Puy
# !@File:月初月末.py

import datetime

# 单独一个日期的月末

print("第一种方式:-------")
year = 2016  # 年
month = 2  # 月
day = 3  # 日

next_month = datetime.date(year, month, day).replace(day=28) + datetime.timedelta(
    days=4)  # this will never fail
res = next_month - datetime.timedelta(days=next_month.day)
year_month_days = res.strftime('%Y-%m-01')
year_month_daye = res.strftime('%Y-%m-%d')
print("月初:", year_month_days)
print("月末:", year_month_daye)

# 一年的12个月的月末

print("第二种方式:-------")
for month in range(1, 13):
    year = 2016  # 年
    # month = 2  # 月
    day = 3  # 日

    next_month = datetime.date(year, month, day).replace(day=28) + datetime.timedelta(
        days=4)  # this will never fail
    res = next_month - datetime.timedelta(days=next_month.day)
    days = res.strftime('%Y-%m-01')
    daye = res.strftime('%Y-%m-%d')
    print("月初:", days)
    print("月末:", daye)

# 加函数方式调用,制定年的12个月的月末

print("第三种方式:-------")
def month_end(year):
    for month in range(1, 13):
        year =year
        day = 3  # 日
        next_month = datetime.date(year, month, day).replace(day=28) + datetime.timedelta(
            days=4)  # this will never fail
        res = next_month - datetime.timedelta(days=next_month.day)
        days = res.strftime('%Y-%m-01')
        daye = res.strftime('%Y-%m-%d')
        print("月初:", days)
        print("月末:", daye)

month_end(2020)
代码数据显示结果

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值