Python classic 100 questions: Determine the day of the year

It can be calculated through the datetime module. The specific implementation is as follows:

import datetime

year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
day = int(input("请输入日期:"))

date = datetime.date(year, month, day)  # 创建date对象

days = (date - datetime.date(year, 1, 1)).days + 1  # 计算天数

print("{}年{}月{}日是本年的第{}天".format(year, month, day, days))

Run the code and enter the year, month and day to get the result. The logical idea is to calculate the number of days between the input date and January 1 of the year, and add 1 to determine the day of the year that the date is.

The following is an upgraded version of Python code, which can determine the day of the year based on the entered date:

import datetime

# 获取输入的日期
date_str = input("请输入一个日期,格式为yyyy-mm-dd: ")

# 将日期字符串转换为日期格式
date = datetime.datetime.strptime(date_str, "%Y-%m-%d")

# 获取该日期所在年份的第一天
first_day = datetime.datetime(date.year, 1, 1)

# 计算日期差,即为该日期是该年的第几天
days = (date - first_day).days + 1

print("该日期是{}年的第{}天。".format(date.year, days))

After running the code, the program will prompt the user to enter a date in the format of "yyyy-mm-dd", for example: "2022-04-01". The program will automatically calculate the day of the year that the date is and output the result.

Guess you like

Origin blog.csdn.net/yechuanhui/article/details/132781602