Convert day number to date in particular year using Python
In this tutorial, we going to learn how to convert day number to date in particular year using Python language. For instance, the day number is 10 in the year 2020 then the date in 2020 is 10th January.
Converting day number to date in a particular year using timedelta()
Firstly we initialize the date by 1st January and then add the number of days using timedelta(), the resultant is the required date.
from datetime import datetime, date, timedelta # initializing day number day_num = input("Enter the day number: ") # adjusting day num day_num.rjust(3 + len(day_num), '0') # Initialize year year = input("Enter the year: ") # Initializing start date start_date = date(int(year), 1, 1) # 1st Jaunary # converting to date result_date = start_date + timedelta(days=int(day_num) - 1) result = result_date.strftime("%d-%m-%Y") print("The day number: " + str(day_num)) print("Date in particular year: " + str(result))
Output
Enter the day number: 210 Enter the year: 2020 The day number: 210 Date in particular year: 28-07-2020
Converting day number to date in a particular year using datetime.strptime()
In this, we get the year and day number, and pass to strptime(), convert to the required date.
from datetime import datetime # initializing day number day_num = input("Enter the day number: ") day_num.rjust(3 + len(day_num), '0') year = input("Enter the year: ") # converting to date res = datetime.strptime(year + "-" + day_num, "%Y-%j").strftime("%d-%m-%Y") print("The day number: " + str(day_num)) print("The date in the particular year: " + str(res))
Output
Enter the day number: 200 Enter the year: 2020 The day number: 200 The date in the particular year: 18-07-2020
Leave a Reply