You can easily obtain yesterday's date in Python using the datetime
module. Here's how:
Using datetime.timedelta
-
Import the
datetime
module:import datetime
-
Get today's date:
today = datetime.date.today()
-
Subtract one day using
timedelta
:yesterday = today - datetime.timedelta(days=1)
-
Print the result:
print(yesterday)
Example:
import datetime
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
print(yesterday)
This code will output yesterday's date in the format YYYY-MM-DD
.
Using date.fromordinal
Another approach is to use the date.fromordinal
method:
-
Import the
datetime
module:import datetime
-
Get today's date:
today = datetime.date.today()
-
Calculate yesterday's ordinal:
yesterday_ordinal = today.toordinal() - 1
-
Convert the ordinal to a date:
yesterday = datetime.date.fromordinal(yesterday_ordinal)
-
Print the result:
print(yesterday)
Example:
import datetime
today = datetime.date.today()
yesterday_ordinal = today.toordinal() - 1
yesterday = datetime.date.fromordinal(yesterday_ordinal)
print(yesterday)
This method also outputs yesterday's date in the format YYYY-MM-DD
.
Both methods achieve the same outcome, providing you with a way to retrieve yesterday's date in your Python code.