- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements