您现在的位置是:首页 » python编程资讯
资讯内容
Python怎么判断是哪一天
极客小将2020-12-19-
简介python判断是哪一天的方法1:先判断是否是闰年,然后再利用求和,得出某一天是第几天# 方法1:low版def func1(year, month, day): # 分别创建平年,闰年的月份天数列表(注
欢迎访问少儿编程网(http://www.pxcodes.com)
Vir少儿编程网-Scratch_Python_教程_免费儿童编程学习平台
python判断是哪一天的Vir少儿编程网-Scratch_Python_教程_免费儿童编程学习平台
方法1:先判断是否是闰年,然后再利用求和,得出某一天是第几天Vir少儿编程网-Scratch_Python_教程_免费儿童编程学习平台
# 方法1:low版 def func1(year, month, day): # 分别创建平年,闰年的月份天数列表(注意列表下标从0开始,而月份是从1月开始,所以1月份对应的下标是0) leap_year = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # 闰年 no_leap_year = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # 判断是否是闰年 if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: # 对列表进行切片处理,获取该月份及之前的所有月份,并对月份天数求和,**后再加上该月份的某一日,即可获得该日期是一年中的第几天 result = sum(leap_year[:month - 1]) + day return result else: result = sum(no_leap_year[:month - 1]) + day return result print(func1(2019, 6, 20)) # 171方法2:使用datetime模块Vir少儿编程网-Scratch_Python_教程_免费儿童编程学习平台
# 方法2 datetime模块 import datetime def func2(y, m, d): sday = datetime.date(y, m, d) # print(type(sday), sday) # <class 'datetime.date'> 2019-06-20 # print(sday.month) # 6 count = sday - datetime.date(sday.year - 1, 12, 31) # 减去上一年**后一天 # 2017-12-31 print(count, type(count)) # 171 days, 0:00:00 <class 'datetime.timedelta'> return '%s是%s年的第%s天' % (sday, y, count.days) print(func2(2019, 6, 20)) # 171方法3:使用内置函数strftimeVir少儿编程网-Scratch_Python_教程_免费儿童编程学习平台
strftime是一种计算机函数,根据区域设置格式化本地时间/日期,函数的功能将时间格式化,或者说格式化一个时间字符串。Vir少儿编程网-Scratch_Python_教程_免费儿童编程学习平台
# 方法3 import datetime def func3(year, month, day): date = datetime.date(year, month, day) return date.strftime('%j') # %j十进制表示的每年的第几天 print(func3(2019, 6, 20)) # 171更多Python知识请关注Python视频教程栏目。Vir少儿编程网-Scratch_Python_教程_免费儿童编程学习平台
- 上一篇
Python 字符串操作常用知识点(1)
简介Python字符串操作常用知识点(1):1、切片:通过索引(索引:索引:步长)截取字符串的一段a = 'ABCDEFGHIJK'print(a[0:3]) # print(a[:3]) 从开头开始取0可以默认不写print
- 下一篇
python实现各种最优化算法
简介python视频教程栏目介绍各种最优化算法相关免费学习推荐:python视频教程二分法函数详见rres,此代码使该算法运行了两次defasdf(x):rres=8*x**3-2*x**2-7*x+3returnrresi=2left=0right=1whilei>0:i=i-1ans=0.1m