python 指定月份的天数、指定日期为周几、指定月份有几个周日、闰年 calender

python 指定月份的天数、指定日期为周几、指定月份有几个周日、闰年 calender

1、指定月份的天数

import calendar
import datetime as dt
date1 = dt.date(2020, 9, 1)
n_days = calendar.monthrange(2020, 9)   # 返回结果:(1, 30)
# calendar.monthrange(year,month):第一个参数:指定月份第一天为周几(0-6 对应 周一 -周日);第二个参数:指定月份的天数

2、指定日期为周几

week = calendar.weekday(2020,9,23)   # 返回结果:2
# calendar.weekday(year,month,day):(0-6 对应 周一 -周日)

3、输出指定月份

calendar.month(2020, 9)   # 返回结果:'   September 2020\nMo Tu We Th Fr Sa Su\n    1  2  3  4  5  6\n 7  8  9 10 11 12 13\n14 15 16 17 18 19 20\n21 22 23 24 25 26 27\n28 29 30\n'
# calendar.month(year, month):指定月份的多行文本字符串

4、获取指定月份所有的日期

date1 = dt.date(2020,9,1)
dates = [(date1 + dt.timedelta(i)) for i in range(n_days[1])]

5、计算指定月份有几个周日

n_sundays = 0
for d in dates:
	n_sundays += int(d.isoweekday() == 6)

6、闰年
(1)判断指定月是否为闰年

calendar.isleap(2020)   # 返回结果:True
# calendar.isleap(year):闰年为True,平年为False

(2)两个年份间的闰年数量

calendar.leapdays(2008, 2020)  # 返回结果:3
# calendar.leapdays(year1, year2):year1与year2年份之间的闰年数量(包括起始年,不包括结束年)

想知道更多,请关注我的公众号~
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值