w3resource

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:

import numpy as np
print("Number of days, February, 2016: ")
print(np.datetime64('2016-03-01') - np.datetime64('2016-02-01'))
print("Number of days, February, 2017: ")
print(np.datetime64('2017-03-01') - np.datetime64('2017-02-01'))
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

Pictorial Presentation:

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

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.

Python: Tips of the Day

Decompose a collection:

Assume we have a function that returns a tuple of two values and we want to assign each value to a separate variable. One way is to use indexing as below:

abc = (5, 10)
x = abc[0]
y = abc[1]
print(x, y)

Output:

5 10

There is a better option that allows us to do the same operation in one line.

x, y = abc
print(x, y)

Output:

5 10

It can be extended to a tuple with more than 2 values or some other data structures such as lists or sets.

x, y, z = {1, 2, 3}
print(x, y, z)
x, y, z = ['a', 'b', 'c']
print(x, y, z)

Output:

1 2 3
a b c