w3resource

NumPy: Display all the dates for the month of March, 2017


Write a NumPy program to display all the dates for the month of March, 2017.

Sample Solution:-

Python Code:

# Importing necessary libraries
import numpy as np

# Displaying the specified range of dates in March 2017 using NumPy's arange function
print("March, 2017")
print(np.arange('2017-03', '2017-04', dtype='datetime64[D]'))

Sample Output:

March, 2017                                                            
['2017-03-01' '2017-03-02' '2017-03-03' '2017-03-04' '2017-03-05'      
 '2017-03-06' '2017-03-07' '2017-03-08' '2017-03-09' '2017-03-10'      
 '2017-03-11' '2017-03-12' '2017-03-13' '2017-03-14' '2017-03-15'      
 '2017-03-16' '2017-03-17' '2017-03-18' '2017-03-19' '2017-03-20'      
 '2017-03-21' '2017-03-22' '2017-03-23' '2017-03-24' '2017-03-25'      
 '2017-03-26' '2017-03-27' '2017-03-28' '2017-03-29' '2017-03-30'      
 '2017-03-31']

Explanation:

print(np.arange('2017-03', '2017-04', dtype='datetime64[D]'))

In the above code –

The interval starts on March 1, 2017 ('2017-03') and ends on March 31, 2017 (the last day before April 1st, '2017-04'). The interval is defined in terms of the number of days between the start and end dates using the datetime64[D] data type, which represents a date as a 64-bit integer, where each unit corresponds to one day.

Therefore, the code generates an array of numpy.datetime64 objects, where each element in the array represents a single day within the specified interval, and the values are separated by one day. The resulting array contains 31 elements, one for each day in March 2017.

Pictorial Presentation:

NumPy: Display all the dates for the month of March, 2017.

Python-Numpy Code Editor: