NumPy: Get the dates of yesterday, today and tomorrow
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:
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics