w3resource

NumPy: Get the dates of yesterday, today and tomorrow

NumPy DateTime: Exercise-2 with Solution

Write a NumPy program to get the dates of yesterday, today and tomorrow.

Sample Solution:-

Python Code:

# Importing necessary libraries
import numpy as np

# Calculating yesterday's date using NumPy's datetime64 and timedelta64
yesterday = np.datetime64('today', 'D') - np.timedelta64(1, 'D')
print("Yestraday: ", yesterday)

# Calculating today's date using NumPy's datetime64
today = np.datetime64('today', 'D')
print("Today: ", today)

# Calculating tomorrow's date using NumPy's datetime64 and timedelta64
tomorrow = np.datetime64('today', 'D') + np.timedelta64(1, 'D')
print("Tomorrow: ", tomorrow) 

Sample Output:

Yestraday:  2017-03-24                                                 
Today:  2017-03-25                                                     
Tomorrow:  2017-03-26

Explanation:

In the above code –

yesterday = np.datetime64('today', 'D') - np.timedelta64(1, 'D'): In this code yesterday is a variable that holds the date value of yesterday. This is achieved by subtracting one day from today's date using the np.timedelta64() function with the argument '1D', which represents one day.

today = np.datetime64('today', 'D'): In this code today is a variable that holds today's date.

tomorrow = np.datetime64('today', 'D') + np.timedelta64(1, 'D'): In this code tomorrow is a variable that holds the date value of tomorrow. This is achieved by adding one day to today's date using the np.timedelta64() function with the argument '1D'.

Pictorial Presentation:

NumPy: Get the dates of yesterday, today and tomorrow.

Python-Numpy Code Editor:

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

Previous: Write a NumPy program to display all the dates for the month of March, 2017.
Next: Write a NumPy program to count the number of days of a given month.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://198.211.115.131/python-exercises/numpy/python-numpy-datetime-exercise-2.php