Python 计算今天(某一日期)是今年中的第几天

 

思路:

1.获取当前日期,分割为,列表分别得当年份、月份、日

2.列表days为12个月中的每个月的天数,默认为平年

3.判断年份是否为闰年,如果是闰年要修改days列表中2月份的天数为29

4.判断时候为1月份,如果是1月份,则直接为当前的日;否则,等于从1月份到上当前月份-1的天数和,加上当前的日期值

from datetime import datetime

cur_date = datetime.now().strftime('%Y-%m-%d').split('-')
# cur_date = input('请输入要计算的日期,例:2021-3-5:').split('-')
print(cur_date)  # 2021-3-5
cur_year = int(cur_date[0])
cur_month = int(cur_date[1])
cur_day = int(cur_date[2])

month_day = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if cur_year % 400 == 0 or (cur_year % 4 == 0 and cur_year % 100 != 0):
    month_day[1] = 29
if cur_month == 1:
    days = cur_day
else:
    days = sum(month_day[0:cur_month - 1]) + cur_day

print(days)

 

posted @ 2021-01-21 14:01  小幸运||  阅读(1786)  评论(0)    收藏  举报