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
Find yesterday's, today's and tomorrow's date in Python
When working with dates in Python, you often need to find yesterday's, today's, and tomorrow's dates. Python's datetime module provides the timedelta class to easily calculate dates relative to the current date.
Basic Date Calculation
Here's how to find yesterday, today, and tomorrow using datetime.now() and timedelta ?
from datetime import datetime, timedelta
present = datetime.now()
yesterday = present - timedelta(1)
tomorrow = present + timedelta(1)
print("Yesterday was :")
print(yesterday.strftime('%d-%m-%Y'))
print("Today is :")
print(present.strftime('%d-%m-%Y'))
print("Tomorrow would be :")
print(tomorrow.strftime('%d-%m-%Y'))
Yesterday was : 05-04-2021 Today is : 06-04-2021 Tomorrow would be : 07-04-2021
Using date() for Date-Only Operations
If you only need dates without time information, use date.today() ?
from datetime import date, timedelta
today = date.today()
yesterday = today - timedelta(days=1)
tomorrow = today + timedelta(days=1)
print(f"Yesterday: {yesterday}")
print(f"Today: {today}")
print(f"Tomorrow: {tomorrow}")
Yesterday: 2021-04-05 Today: 2021-04-06 Tomorrow: 2021-04-07
Custom Date Formatting
You can format dates in various ways using strftime() ?
from datetime import date, timedelta
today = date.today()
yesterday = today - timedelta(days=1)
tomorrow = today + timedelta(days=1)
print(f"Yesterday: {yesterday.strftime('%B %d, %Y')}")
print(f"Today: {today.strftime('%A, %B %d, %Y')}")
print(f"Tomorrow: {tomorrow.strftime('%d/%m/%Y')}")
Yesterday: April 05, 2021 Today: Tuesday, April 06, 2021 Tomorrow: 07/04/2021
How It Works
datetime.now()returns the current date and timedate.today()returns only the current date without timetimedelta(days=1)represents a duration of one dayAdding
timedeltamoves forward in time, subtracting moves backwardstrftime()formats dates into readable strings using format codes
Conclusion
Use timedelta with datetime.now() or date.today() to calculate relative dates. The strftime() method allows flexible date formatting for display purposes.
