Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Day of the Year in Python
Sometimes we need to find which day of the year a specific date represents. For example, February 10th, 2019 is the 41st day of the year. Python provides several ways to calculate this using date manipulation.
Algorithm Approach
To calculate the day of the year manually, we follow these steps −
- Create an array of days in each month: [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
- Parse the date string to extract year, month, and day
- Check if the year is a leap year and adjust February days to 29
- Sum up all days from months 1 to (month-1) plus the current day
Manual Implementation
class Solution:
def dayOfYear(self, date):
# Days in each month (index 0 is placeholder)
days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# Parse date string into year, month, day
year, month, day = map(int, date.split("-"))
# Check for leap year
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
days[2] = 29 # February has 29 days in leap year
# Convert to cumulative days
for i in range(1, len(days)):
days[i] += days[i-1]
# Return cumulative days up to previous month + current day
return days[month-1] + day
# Test the solution
solution = Solution()
print(solution.dayOfYear("2019-02-10"))
print(solution.dayOfYear("2020-02-29")) # Leap year test
41 60
Using Python's datetime Module
Python's built-in datetime module provides a simpler approach using the timetuple() method ?
from datetime import datetime
def day_of_year_datetime(date_string):
date_obj = datetime.strptime(date_string, "%Y-%m-%d")
return date_obj.timetuple().tm_yday
# Test with different dates
print(day_of_year_datetime("2019-02-10"))
print(day_of_year_datetime("2020-12-31")) # Last day of leap year
print(day_of_year_datetime("2021-12-31")) # Last day of regular year
41 366 365
Using strftime Method
Another concise approach uses the strftime() method with the %j format code ?
from datetime import datetime
def day_of_year_strftime(date_string):
date_obj = datetime.strptime(date_string, "%Y-%m-%d")
return int(date_obj.strftime("%j"))
# Test the function
print(day_of_year_strftime("2019-02-10"))
print(day_of_year_strftime("2019-01-01")) # First day
print(day_of_year_strftime("2019-12-31")) # Last day
41 1 365
Comparison of Methods
| Method | Complexity | Best For |
|---|---|---|
| Manual calculation | More code | Understanding the algorithm |
| timetuple().tm_yday | Simple | Readable and clear |
| strftime("%j") | Very simple | One-liner solution |
Conclusion
Use datetime.strptime() with strftime("%j") for the simplest solution. The manual approach helps understand leap year calculations and cumulative day counting.
Advertisements
