w3resource

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


1. March 2017 Dates

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.

For more Practice: Solve these Related Problems:

  • Generate all dates for a given month and year using np.arange with np.datetime64 and verify the output format.
  • Create a function that returns an array of dates for March 2017 and computes the corresponding weekday names.
  • Extract only weekend dates from March 2017 using vectorized date arithmetic and boolean indexing.
  • Convert the March 2017 date array into a custom string format (e.g., "Mar 01, 2017") using vectorized string operations.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous:NumPy DateTime Exercises Home.
Next: Write a NumPy program to get the dates of yesterday, today and tomorrow.

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.