NumPy: Count the number of days of specific month
NumPy DateTime: Exercise-3 with Solution
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:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a NumPy program to get the dates of yesterday, today and tomorrow.
Next: Write a Python program to create 24 python datetime. datetime objects (single object for every hour), and then put it in a numpy array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/numpy/python-numpy-datetime-exercise-3.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics