使用NumPy计算特定月份的天数
为了计算一个特定月份的天数,我们将使用numpy模块的numpy.datetime64()方法。
示例:
Input: month = 2; year = 2016
Output: 29 days
Input: month = 12; year = 2020
Output: 31 days
让我们假设我们要计算天数的月份是P,下个月是N。 我们将从N月份的第一个日期中减去P月份的第一个日期。 在numpy.datetime64()方法中实现这一点。
语法:
除12月外的所有月份。
numpy.datetime64('yyyy-N-01') - numpy.datetime64(yyyy-P-01')
For December:
numpy.datetime64('yyyy-P-31') - numpy.datetime64(yyyy-P-01') + 1
下面是各种例子,描述了如何使用numpy模块计算特定月份的天数。
示例 #1:
在这个例子中,我们将找到2016年2月的天数。
# import module
import numpy
# explicit function to calculate
# number of days
def calcDays(month, year):
date = 0
# December case
if month == 12:
end = str(year)+'-'+str(month)+'-31'
begin = str(year)+'-'+str(month)+'-01'
date = 1
else:
# single digit months
if month < 10:
endM = '-0'+str(month+1)
beginM = '-0'+str(month)
# double digit months
else:
endM = '-'+str(month+1)
beginM = '-'+str(month)
end = str(year)+endM+'-01'
begin = str(year)+beginM+'-01'
# return number of days
return (numpy.datetime64(end) - numpy.datetime64(begin)+date)
# Driver Code
# get month
month = 2
# get year
year = 2016
# call the function
print(calcDays(month, year))
输出:
29 days
示例 #2:
在这里,我们将找到2001年4月份的天数。
# import module
import numpy
# explicit function to calculate
# number of days
def calcDays(month, year):
date = 0
# December case
if month == 12:
end = str(year)+'-'+str(month)+'-31'
begin = str(year)+'-'+str(month)+'-01'
date = 1
else:
# single digit months
if month < 10:
endM = '-0'+str(month+1)
beginM = '-0'+str(month)
# double digit months
else:
endM = '-'+str(month+1)
beginM = '-'+str(month)
end = str(year)+endM+'-01'
begin = str(year)+beginM+'-01'
# return number of days
return (numpy.datetime64(end) - numpy.datetime64(begin)+date)
# Driver Code
# get month
month = 4
# get year
year = 2001
# call the function
print(calcDays(month, year))
输出:
30 days
示例 #3:
在下面的程序中,我们将找出2021年12月份的天数。
# import module
import numpy
# explicit function to calculate
# number of days
def calcDays(month, year):
date = 0
# December case
if month == 12:
end = str(year)+'-'+str(month)+'-31'
begin = str(year)+'-'+str(month)+'-01'
date = 1
else:
# single digit months
if month < 10:
endM = '-0'+str(month+1)
beginM = '-0'+str(month)
# double digit months
else:
endM = '-'+str(month+1)
beginM = '-'+str(month)
end = str(year)+endM+'-01'
begin = str(year)+beginM+'-01'
# return number of days
return (numpy.datetime64(end) - numpy.datetime64(begin)+date)
# Driver Code
# get month
month = 12
# get year
year = 2021
# call the function
print(calcDays(month, year))
输出:
31 days