Print dates of today, yesterday and tomorrow using Numpy


In this program, we will print today's, yesterday's and tomorrow's dates using the numpy library.

Algorithm

Step 1: Import the numpy library.
Step 2: find today's date using the datetime64() function.
Step 3: find yesterday's date by subtracting the output of timedelta64() function from the output of datetime64() function.
Step 4: Find yesterday's date by adding the output of timedelta64() function from the output of datetime64() function.

Example Code

import numpy as np

todays_date = np.datetime64('today', 'D')
print("Today's Date: ", todays_date)

yesterdays_date = np.datetime64('today', 'D') - np.timedelta64(1, 'D')
print("Yesterday's Date: ", yesterdays_date)

tomorrows_date = np.datetime64('today', 'D') + np.timedelta64(1, 'D')
print("Tomorrow's Date: ", tomorrows_date)

Output

Today's Date: 2021-02-16
Yesterday's Date: 2021-02-15
Tomorrow's Date: 2021-02-17

Explanation

In numpy, there are data types which support datetime functionality. The name 'datetime64' is given to the function because the name 'datetime' is already taken by a library in Python.

The 'D' parameter in the datetime64() function is for getting the date in a 'days' unit. timedelta64() function is used for expressing difference in times for example, days, hours, minutes, seconds.

Updated on: 16-Mar-2021

281 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements