w3resource

NumPy: Count the number of days of specific month


3. Count Days in a 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:

NumPy: Count the number of days of a given month.

For more Practice: Solve these Related Problems:

  • Write a function that calculates the number of days in February for both leap and non-leap years using np.datetime64 arithmetic.
  • Compute the number of days in any given month by creating an array of dates for that month and counting its length.
  • Compare the day counts for February in different years using np.busday_count to handle business days versus calendar days.
  • Implement a solution that subtracts the first day from the last day of a month (plus one) to get the total count, and test it for multiple months.

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.



Follow us on Facebook and Twitter for latest update.