Skip to content
Related Articles

Related Articles

How to display the days of the week for a particular year using Pandas?

View Discussion
Improve Article
Save Article
  • Last Updated : 29 Aug, 2020
View Discussion
Improve Article
Save Article

Given the day and the year. The task is to display all the days of the week of the given year. It can be found using the pandas.date_range() function. This function is used to get a fixed frequency DatetimeIndex.

Syntax: pandas.date_range(start=None, end=None, periods=None, freq=None, tz=None, normalize=False, name=None, closed=None, **kwargs)

Approach:

  • Import pandas module
  • Create a  parameter function for computing the time series.
  • Generate sequences of fixed-frequency dates with pandas.date_range() within the function
  • Store into the pandas series within the function
  • And return the all-day of date

Below is the implementation.

Python3




# importing module
import pandas as pd
  
  
# User define function
def Time_series(day, yy):
    date_range = pd.date_range(yy+'-01-01', periods=52, freq=day)
    result = pd.Series(date_range)
    print(f"All { day[2:] } in " + yy + ":")
    print(result)
  
  
# Input from user
day = "wed"
yy = "2020"
  
# Check the day form input variable
if day == 'monday' or day == 'mon':
    Time_series('W-mon', yy)
elif day == 'tuesday' or day == 'tue':
    Time_series('W-tue', yy)
elif day == 'wednesday' or day == 'wed':
    Time_series('W-wed', yy)
elif day == 'thursday' or day == 'thu':
    Time_series('W-thu', yy)
elif day == 'friday' or day == 'fri':
    Time_series('W-fri', yy)
elif day == 'saturday' or day == 'sat':
    Time_series('W-fri', yy)
else:
    Time_series('W-sun', yy)

Output :

All wed in 2020:
0    2020-01-01
1    2020-01-08
2    2020-01-15
3    2020-01-22
4    2020-01-29
5    2020-02-05
6    2020-02-12
7    2020-02-19
8    2020-02-26
9    2020-03-04
10   2020-03-11
11   2020-03-18
12   2020-03-25
13   2020-04-01
14   2020-04-08
15   2020-04-15
16   2020-04-22
17   2020-04-29
18   2020-05-06
19   2020-05-13
20   2020-05-20
21   2020-05-27
22   2020-06-03
23   2020-06-10
24   2020-06-17
25   2020-06-24
26   2020-07-01
27   2020-07-08
28   2020-07-15
29   2020-07-22
30   2020-07-29
31   2020-08-05
32   2020-08-12
33   2020-08-19
34   2020-08-26
35   2020-09-02
36   2020-09-09
37   2020-09-16
38   2020-09-23
39   2020-09-30
40   2020-10-07
41   2020-10-14
42   2020-10-21
43   2020-10-28
44   2020-11-04
45   2020-11-11
46   2020-11-18
47   2020-11-25
48   2020-12-02
49   2020-12-09
50   2020-12-16
51   2020-12-23
dtype: datetime64[ns]

Note: Periods 52 because the total number of days in a year is 365 then each day will repeat 52 times (365/7=52).


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!