Count the number of days of a specific month using NumPy
Last Updated :
02 Dec, 2020
In order to count the number of days of a specific month, we will be using numpy.datetime64() method of numpy module.
Examples:
Input: month = 2; year = 2016
Output: 29 days
Input: month = 12; year = 2020
Output: 31 days
Let us assume the month whose number of days we want to count be P and the next month is N. We will subtract the first date of the month P from the first date of the month N. Implementing this in numpy.datetime64() method.
Syntax:
For all months except December:
numpy.datetime64('yyyy-N-01') - numpy.datetime64(yyyy-P-01')
For December:
numpy.datetime64('yyyy-P-31') - numpy.datetime64(yyyy-P-01') + 1
Below are various examples which depict how to count the number of days of a specific month using numpy module:
Example #1:
In this example, we will find the number of days in the month of February of the year 2016.
Python3
import numpy
def calcDays(month, year):
date = 0
if month = = 12 :
end = str (year) + '-' + str (month) + '-31'
begin = str (year) + '-' + str (month) + '-01'
date = 1
else :
if month < 10 :
endM = '-0' + str (month + 1 )
beginM = '-0' + str (month)
else :
endM = '-' + str (month + 1 )
beginM = '-' + str (month)
end = str (year) + endM + '-01'
begin = str (year) + beginM + '-01'
return (numpy.datetime64(end) - numpy.datetime64(begin) + date)
month = 2
year = 2016
print (calcDays(month, year))
|
Output:
29 days
Example #2:
Here, we will find the number of days in the month of April of the year 2001.
Python3
import numpy
def calcDays(month, year):
date = 0
if month = = 12 :
end = str (year) + '-' + str (month) + '-31'
begin = str (year) + '-' + str (month) + '-01'
date = 1
else :
if month < 10 :
endM = '-0' + str (month + 1 )
beginM = '-0' + str (month)
else :
endM = '-' + str (month + 1 )
beginM = '-' + str (month)
end = str (year) + endM + '-01'
begin = str (year) + beginM + '-01'
return (numpy.datetime64(end) - numpy.datetime64(begin) + date)
month = 4
year = 2001
print (calcDays(month, year))
|
Output:
30 days
Example #3:
In the below program, we will find the number of days in the month of December of the year 2021.
Python3
import numpy
def calcDays(month, year):
date = 0
if month = = 12 :
end = str (year) + '-' + str (month) + '-31'
begin = str (year) + '-' + str (month) + '-01'
date = 1
else :
if month < 10 :
endM = '-0' + str (month + 1 )
beginM = '-0' + str (month)
else :
endM = '-' + str (month + 1 )
beginM = '-' + str (month)
end = str (year) + endM + '-01'
begin = str (year) + beginM + '-01'
return (numpy.datetime64(end) - numpy.datetime64(begin) + date)
month = 12
year = 2021
print (calcDays(month, year))
|
Output:
31 days
Share your thoughts in the comments
Please Login to comment...