Home > Net >  Create a dataframe containing all weekends in a given year
Create a dataframe containing all weekends in a given year

Time:04-02

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:

def get_saturdays_and_sundays(year):
   df = pd.DataFrame()
   # Generate dataframe
   return df

def main():
   print(get_saturdays_and_sundays(2022))

if __name__ == '__main__':  
    main()

The function would return:

|      date                 |     day          |
|---------------------------|------------------|
|          2022-01-01       |     Saturday     |
|          2022-01-02       |     Sunday       |
|          2022-01-08       |     Saturday     |
|          2022-01-09       |     Sunday       |
...
|          2022-12-24       |     Saturday     |
|          2022-12-25       |     Sunday       |
|          2022-12-31       |     Saturday     |

If you can tell me an optimal way to get that dataframe I would be grateful.

CodePudding user response:

Well here's my finished code. I think yours wasn't working because you didn't write anything.

from datetime import datetime
from datetime import timedelta
import calendar
import pandas as pd
import numpy as np


def daysInYear(year):
    beginningOfYear = datetime.strptime(f"{year}",r"%Y")
    days = []
   
    for day_offset in range(365 calendar.isleap(year)):
        today = beginningOfYear timedelta(days=day_offset,hours=1)
        days.append(today)
    return pd.Series(days)
def get_saturdays_and_sundays(year):

    daysInYearAndDayOfWeek = pd.DataFrame({"Date":daysInYear(year)})
    daysInYearAndDayOfWeek["Day Of The Week"] = daysInYearAndDayOfWeek["Date"].map(lambda date: calendar.day_name[date.weekday()])
    
    return daysInYearAndDayOfWeek[(daysInYearAndDayOfWeek["Day Of The Week"]=="Saturday") | (daysInYearAndDayOfWeek["Day Of The Week"]=="Sunday")]
    
x = get_saturdays_and_sundays(2018)
print(x)
  • Related