﻿ Python: Convert Year/Month/Day to Day of Year - w3resource

# Python: Convert Year/Month/Day to Day of Year

## Python datetime: Exercise-11 with Solution

Write a Python program to convert Year/Month/Day to Day of Year in Python.

Sample Solution:

Python Code:

`````` # Import the datetime module
import datetime

# Get the current date and time and assign it to the variable 'today'
today = datetime.datetime.now()

# Calculate the day of the year by subtracting January 1st of the current year from the current date and time,
# then retrieve the number of days and add 1 (since January 1st should be considered as day 1)
day_of_year = (today - datetime.datetime(today.year, 1, 1)).days + 1

# Print the calculated day of the year
print(day_of_year)
```
```

Output:

```126
```

Explanation:

In the exercise above,

• The code imports the datetime module, which provides functionalities to work with dates and times.
• Get the current date and time:
• It retrieves the current date and time using "datetime.datetime.now()" and assigns it to the variable 'today'.
• Calculating the day of the year:
• It calculates the day of the year by subtracting January 1st of the current year from the current date and time. This effectively gives the number of days elapsed since the start of the year.
• It retrieves the number of days from the resulting timedelta object and adds 1 to account for January 1st, which should be considered as day 1.
• Finally it prints the calculated day of the year using "print(day_of_year)".

Flowchart:

Python Code Editor: