﻿ NumPy: Get the dates of yesterday, today and tomorrow - 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')

# 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: Python-Numpy Code Editor:

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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿