w3resource

NumPy: Find the first Monday in May 2017


Write a NumPy program to find the first Monday in May 2017.

Sample Solution:

Python Code:

# Importing the required libraries
import numpy as np

# Finding the first Monday in May 2017 using numpy's busday_offset function
# The '2017-05' indicates the month (May) and '0' indicates the starting day (1st)
# 'roll='forward'' ensures that if the given date is not a business day (Monday), it will roll forward to the next Monday
# 'weekmask='Mon'' specifies that only Mondays are considered as business days
print("First Monday in May 2017:")
print(np.busday_offset('2017-05', 0, roll='forward', weekmask='Mon')) 

Sample Output:

First Monday in May 2017:                                              
2017-05-01 

Explanation:

The above exercise finds the date of the first Monday in May 2017.

np.busday_offset('2017-05', 0, roll='forward', weekmask='Mon'):

In the above code –

  • np.busday_offset() is a function that calculates the next or previous business day, given a starting date, a number of offset days, and an optional weekmask.
  • '2017-05' is the starting date, representing May 2017.
  • 0 is the offset, meaning no days are added or subtracted from the starting date.
  • roll='forward' specifies that the offset should be added to the starting date to find the next business day, in case the starting date is not a business day.
  • weekmask='Mon' specifies that only Mondays are considered as business days.
  • The result of np.busday_offset() is the first Monday in May 2017, which is May 1st.

Pictorial Presentation:

NumPy: Find the first Monday in May 2017.

Python-Numpy Code Editor: