Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find number of Mondays or any other weekday between two dates in Python?

I have two dates between which I need to find out how many Mon- Fri are coming(except for Sta, Sun), everyday should be counted

Currently I am thinking this:

import calendar
import datetime
start_date = datetime.datetime.strptime("01/01/2017",'%d/%m/%Y')
end_date = datetime.datetime.strptime("31/01/2017",'%d/%m/%Y')
week_arr = [0] * 7
calendar.day_name[start_date.weekday()] ## will give me name of day
"""
As I receive Monday I will increment week_arr[0] by 1, Tuesday
week_arr[1]+= 1,
"""

I am not getting how to do it effectively so that I dont use much line of code(less if -else and for loops), may be some tricks in pandas.

like image 233
Deep Dwivedi Avatar asked Apr 29 '17 06:04

Deep Dwivedi


People also ask

How do you get the Monday of the week in Python?

Algorithm (Steps) Use the import keyword, to import the ,datetime(To work with dates and times) module. Use the today() function(gets the current local date), to get today's current local date and print it. Increment the Today's date with 1 week by passing the weeks as 1 as an argument to the timedelta() function.

How do I get weekday numbers in Python?

Use the weekday() method The weekday() method returns the day of the week as an integer, where Monday is 0 and Sunday is 6. For example, the date(2022, 05, 02) is a Monday. So its weekday number is 0.


2 Answers

You can define a function and use it like this :

def num_days_between( start, end, week_day):
    num_weeks, remainder = divmod( (end-start).days, 7)
    if ( week_day - start.weekday() ) % 7 < remainder:
       return num_weeks + 1
    else:
       return num_weeks

where week_day is day number you wan to calculate count.

like image 152
mohammad Avatar answered Sep 18 '22 17:09

mohammad


Number of Mondays in 2020 can be got using numpy library

    import numpy as np
    np.busday_count('2020', '2021', weekmask='Mon')
like image 21
Priyom Avatar answered Sep 21 '22 17:09

Priyom