Python小技 打印月初月末
程序员文章站
2022-05-15 09:16:57
...
使用datetime模块打印月初与月末
#!usr/bin/env python3
# -*- coding: UTF-8 -*-
# [email protected]:2020/9/9 10:22
# [email protected]:Puy
# [email protected]:月初月末.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)
代码数据显示结果
上一篇: 获取本月月末和月初的时间戳(秒)
下一篇: 计算某个月的月初和月末