Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Print dates of today, yesterday and tomorrow using Numpy
NumPy provides datetime functionality through the datetime64 data type, allowing you to easily work with dates. You can calculate today's, yesterday's, and tomorrow's dates using np.datetime64() and np.timedelta64() functions.
Understanding DateTime64
The datetime64 function creates date objects, while timedelta64 represents time differences. The 'D' parameter specifies the unit as days −
import numpy as np
# Get today's date
today = np.datetime64('today', 'D')
print("Today's Date:", today)
Today's Date: 2024-01-15
Calculating Yesterday and Tomorrow
You can add or subtract timedelta64 objects to get past or future dates ?
import numpy as np
# Calculate all three dates
todays_date = np.datetime64('today', 'D')
yesterdays_date = todays_date - np.timedelta64(1, 'D')
tomorrows_date = todays_date + np.timedelta64(1, 'D')
print("Today's Date:", todays_date)
print("Yesterday's Date:", yesterdays_date)
print("Tomorrow's Date:", tomorrows_date)
Today's Date: 2024-01-15 Yesterday's Date: 2024-01-14 Tomorrow's Date: 2024-01-16
Working with Different Time Units
You can also work with other time units like hours, minutes, or weeks ?
import numpy as np
today = np.datetime64('today', 'D')
# Using different time units
last_week = today - np.timedelta64(7, 'D')
next_week = today + np.timedelta64(1, 'W')
print("Today:", today)
print("Last week:", last_week)
print("Next week:", next_week)
Today: 2024-01-15 Last week: 2024-01-08 Next week: 2024-01-21
Key Points
- The function is named
datetime64becausedatetimeis already used by Python's standard library - The 'D' parameter specifies the unit as days
- Use
timedelta64()to add or subtract time periods - Other common units include 'W' (weeks), 'h' (hours), 'm' (minutes)
Conclusion
NumPy's datetime64 and timedelta64 functions provide a simple way to work with dates. Use these functions to calculate past and future dates by adding or subtracting time deltas from the current date.
