
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Day of the Year in Python
Suppose, we have a date in the format “YYYY-MM-DD”. We have to return the day number of the year. So if the date is “2019-02-10”, then this is 41st day of the year.
To solve this, we will follow these steps −
- Suppose D is an array of day count like [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
- Convert the date into list of year, month and day
- if the year is leap year then set date D[2] = 29
- Add up the day count up to the month mm – 1. and day count after that.
Example
Let us see the following implementation to get better understanding −
class Solution(object): def dayOfYear(self, date): days = [0,31,28,31,30,31,30,31,31,30,31,30,31] d = list(map(int,date.split("-"))) if d[0] % 400 == 0: days[2]+=1 elif d[0]%4 == 0 and d[0]%100!=0: days[2]+=1 for i in range(1,len(days)): days[i]+=days[i-1] return days[d[1]-1]+d[2] ob1 = Solution() print(ob1.dayOfYear("2019-02-10"))
Input
"2019-02-10"
Output
41
- Related Articles
- Python Pandas - Get the Day of the year from Period object
- Convert day of year to day of month in Java
- Python Pandas - Create a PeriodIndex and get the day of the year
- Find number of times every day occurs in a Year in Python
- Display three-digit day of the year in Java
- Python Pandas - Indicate whether the date in DateTimeIndex is the first day of the year
- Python Pandas - Indicate whether the date in DateTimeIndex is the last day of the year
- Finding day of week from date (day, month, year) in JavaScript
- Select last day of current year in MySQL?
- How to calculate / get day of the year in Excel?
- Write a program in Python to print the day of the year in a given date series
- Filter the records of current day, month and year in MySQL?
- How to find the day of the year from dates in R?
- Python Pandas - Extract the ordinal day of year from the DateTimeIndex with specific time series frequency
- How to get day of month, day of year and day of week in android using offset date time API class?

Advertisements