w3resource

NumPy: Find the first Monday in May 2017

NumPy DateTime: Exercise-5 with Solution

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:

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

Previous: Write a NumPy program to create 24 python datetime. datetime objects (single object for every hour), and then put it in a numpy array.
Next: Write a NumPy program to find the number of weekdays in March 2017.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/python-numpy-datetime-exercise-5.php