NumPy: Count the number of days of specific month
Write a NumPy program to count the number of days of specific month.
Sample Solution:
Python Code:
# Importing necessary libraries
import numpy as np
# Calculating the number of days in February 2016 using datetime64
print("Number of days, February, 2016: ")
print(np.datetime64('2016-03-01') - np.datetime64('2016-02-01'))
# Calculating the number of days in February 2017 using datetime64
print("Number of days, February, 2017: ")
print(np.datetime64('2017-03-01') - np.datetime64('2017-02-01'))
# Calculating the number of days in February 2018 using datetime64
print("Number of days, February, 2018: ")
print(np.datetime64('2018-03-01') - np.datetime64('2018-02-01'))
Sample Output:
Number of days, February, 2016: 29 days Number of days, February, 2017: 28 days Number of days, February, 2018: 28 days
Explanation:
In the above exercise –
np.datetime64('2016-03-01') - np.datetime64('2016-02-01') - This code subtracts the datetime '2016-02-01' from '2016-03-01' using the '-' operator provided by NumPy.
np.datetime64('2017-03-01') - np.datetime64('2017-02-01') - This code does the same operation as above, but with dates from 2017. The result is a timedelta of 28 days, since February has 28 days in 2017.
np.datetime64('2018-03-01') - np.datetime64('2018-02-01') - This code does the same operation as above, but with dates from 2018. The result is also a timedelta of 28 days, since February still has 28 days in 2018.
Pictorial Presentation:
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics