w3resource

NumPy: Find the number of weekdays in March 2017


6. Number of Weekdays in March 2017

Write a NumPy program to find the number of weekdays in March 2017.

Note: "busday" default of Monday through Friday being valid days.

Sample Solution:

Python Code:

# Importing the required libraries
import numpy as np

# Finding the number of weekdays in March 2017 using numpy's busday_count function
# '2017-03' indicates the start of the period (March 2017)
# '2017-04' indicates the end of the period (April 2017), but this day is not counted
# The function calculates the number of weekdays (excluding weekends) between the provided dates
print("Number of weekdays in March 2017:")
print(np.busday_count('2017-03', '2017-04')) 

Sample Output:

Number of weekdays in March 2017:                                      
23 

Explanation:

The above NumPy exercise returns the number of business days between the start and end dates (inclusive) excluding weekends and any holidays that fall in-between.

np.busday_count('2017-03', '2017-04'):

In the above code –

  • np.busday_count() function is used to calculate the number of business days between two dates.
  • The first argument '2017-03' is the start date, and the second argument '2017-04' is the end date (exclusive).
  • The function returns the number of business days between these two dates, which is the number of weekdays excluding any holidays that occur in between.
  • In this case, it returns 23 because March 2017 has 23 weekdays

Pictorial Presentation:

NumPy: Find the number of weekdays in March 2017.

For more Practice: Solve these Related Problems:

  • Calculate the number of business days in March 2017 using np.busday_count with default settings.
  • Create a function that takes a month and year and returns the count of weekdays by generating an array of dates and applying np.is_busday.
  • Compare the computed weekday count for March 2017 with that of another month to analyze differences.
  • Implement a solution that identifies the indices of all weekdays in March 2017 and verifies the total count matches expected values.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a NumPy program to find the first Monday in May 2017.
Next: Write a NumPy program to convert numpy datetime64 to Timestamp.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.