如何使用 NumPy 查找给定月份的第一个星期一?
要找到给定月份的第一个星期一,我们将使用numpy模块,即numpy模块中的numpy.busday_offset()方法。
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.
下面是一些使用numpy.busday_offset()方法获取一个月的第一个星期一的程序:
示例#1:
在此示例中,我们将找到 2017 年 5 月的第一个星期一。
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)
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)
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)
输出:
2017-05-01
示例#2:
在这里,我们将找到 2001 年 2 月的第一个星期一。
蟒蛇3
# 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)
输出:
2001-02-05
示例#3:
在这里,我们将找到 2020 年 11 月的第一个星期一。
蟒蛇3
# 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)
输出:
2001-11-02