Good afternoon,
I would like to create a function that, given a year, would return a dataframe with all the dates in Timestamp format related to the Saturdays and Sundays of that year. That is to say:
JavaScript
x
11
11
1
def get_saturdays_and_sundays(year):
2
df = pd.DataFrame()
3
# Generate dataframe
4
return df
5
6
def main():
7
print(get_saturdays_and_sundays(2022))
8
9
if __name__ == '__main__':
10
main()
11
The function would return:
JavaScript
1
11
11
1
| date | day |
2
|---------------------------|------------------|
3
| 2022-01-01 | Saturday |
4
| 2022-01-02 | Sunday |
5
| 2022-01-08 | Saturday |
6
| 2022-01-09 | Sunday |
7
8
| 2022-12-24 | Saturday |
9
| 2022-12-25 | Sunday |
10
| 2022-12-31 | Saturday |
11
If you can tell me an optimal way to get that dataframe I would be grateful.
Advertisement
Answer
Well here’s my finished code. I think yours wasn’t working because you didn’t write anything.
JavaScript
1
25
25
1
from datetime import datetime
2
from datetime import timedelta
3
import calendar
4
import pandas as pd
5
import numpy as np
6
7
8
def daysInYear(year):
9
beginningOfYear = datetime.strptime(f"{year}",r"%Y")
10
days = []
11
12
for day_offset in range(365+calendar.isleap(year)):
13
today = beginningOfYear+timedelta(days=day_offset,hours=1)
14
days.append(today)
15
return pd.Series(days)
16
def get_saturdays_and_sundays(year):
17
18
daysInYearAndDayOfWeek = pd.DataFrame({"Date":daysInYear(year)})
19
daysInYearAndDayOfWeek["Day Of The Week"] = daysInYearAndDayOfWeek["Date"].map(lambda date: calendar.day_name[date.weekday()])
20
21
return daysInYearAndDayOfWeek[(daysInYearAndDayOfWeek["Day Of The Week"]=="Saturday") | (daysInYearAndDayOfWeek["Day Of The Week"]=="Sunday")]
22
23
x = get_saturdays_and_sundays(2018)
24
print(x)
25