Python怎么判断是哪一天
发布时间:2026-04-17 15:42:05

python判断是哪一天?
方法1:先判断是否是闰年,再利用求和,得出某一天是第一天
#方法1:low版 deffunc1(year,month,day): #平年和闰年的月天数列表分别创建(注意列表下标从0开始,月份从1月开始,所以1月对应的下标是0) leap_year=#闰年,31,31,31,31,31,31,31,31,31,31,31 no_leap_year=31,31,31,31,31,31,31,31,31,31,31,31 #判断是否是闰年 if(year%4==0andyear%100!=0)oryear%400==0: #对列表进行切片处理,获取本月及以前的所有月份,并与本月天数进行总和。最后,加上本月的某一天,你可以得到一年中的第一天 result=sum(leap_year[:month-1])+day returnresult else: result=sum(no_leap_year[:month-1])+day returnresult print#171(func1)
方法2:使用datetime模块
#2datetime模块方法 importdatetime deffunc2(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))#171days,0:00:00<class'datetime.timedelta'> return'%是%s年的第%s天'%(sday,y,count.days) print#171
方法3:strftime使用内置函数
strftime是一种根据区域设置格式化本地时间/日期的计算机函数。函数的功能是格式化时间或格式化时间字符串。
#方法3
importdatetime
deffunc3(year,month,day):
date=datetime.date(year,month,day)
returndate.strftime('%j')#%J0进制表示每年的第几天
print(func3(2019,6,20)#171请关注Python视频教程栏目,了解更多Python知识。
下一篇 python如何把字符转小写字母
