Skip to content
Related Articles
Open in App
Not now

Related Articles

How to find the first Monday of a given month using NumPy?

Improve Article
Save Article
  • Last Updated : 02 Dec, 2020
Improve Article
Save Article

To find the first Monday of a given month, we are going to use the numpy module i.e the numpy.busday_offset() method in numpy module.

Syntax: np.busday_offset(‘date’, 0, roll=’forward’, weekmask=’Mon’)

Parameters:

date: The array of dates to process.

offsets: The array of offsets, which is broadcast with dates.

roll:It takes the below values:

  • raise means to raise an exception for an invalid day.
  • nat means to return a NaT (not-a-time) for an invalid day.
  • forward and following mean to take the first valid day later in time.
  • backward and preceding mean to take the first valid day earlier in time.
  • modifiedfollowing means to take the first valid day later in time unless it is across a Month boundary, in which case to take the first valid day earlier in time.
  • modifiedpreceding means to take the first valid day earlier in time unless it is across a Month boundary, in which case to take the first valid day later in time.

weekmask: array indicating which of Monday through Sunday are valid days.

Returns (outarray of datetime64): An array with a shape from broadcasting dates and offsets together, containing the dates with offsets applied.

Below are some programs which use numpy.busday_offset() method to get first Monday of a month:

Example #1:

In this example, we will find the first Monday of the month of May 2017.

Python3




# import module
import numpy
  
# input year and month
yearMonth = '2017-05'
  
# getting date of first monday
date = numpy.busday_offset(yearMonth, 0
                           roll='forward'
                           weekmask='Mon')
  
# display date
print(date)

Output:

2017-05-01

Example #2:

Here, we will find the first Monday of the month of February 2001.

Python3




# import module
import numpy
  
# input year and month
yearMonth = '2001-02'
  
# getting date of first monday
date = numpy.busday_offset(yearMonth, 0,
                           roll='forward',
                           weekmask='Mon')
  
# display date
print(date)

Output:

2001-02-05

Example #3:

Here, we will find the first Monday of the month of November 2020.

Python3




# import module
import numpy
  
# input year and month
yearMonth = '2020-11'
  
# getting date of first monday
date = numpy.busday_offset(yearMonth, 0,
                           roll='forward',
                           weekmask='Mon')
  
# display date
print(date)

Output:

2001-11-02

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!