Python - Get Yesterday's date as a string in YYYY-MM-DD format
You Just need to subtract one day from today's date. In Python datetime.timedelta
object lets you create specific spans of time as a timedelta
object.
datetime.timedelta(1)
gives you the duration of "one day" and is subtractable from a datetime
object. After you subtracted the objects you can use datetime.strftime
in order to convert the result --which is a date object-- to string format based on your format of choice:
>>> from datetime import datetime, timedelta
>>> yesterday = datetime.now() - timedelta(1)
>>> type(yesterday)
>>> datetime.datetime
>>> datetime.strftime(yesterday, '%Y-%m-%d')
'2015-05-26'
Note that instead of calling the datetime.strftime
function, you can also directly use strftime
method of datetime
objects:
>>> (datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
'2015-05-26'
As a function:
def yesterday(string=False):
yesterday = datetime.now() - timedelta(1)
if string:
return yesterday.strftime('%Y-%m-%d')
return yesterday
An alternative answer that uses today()
method to calculate current date and then subtracts one using timedelta()
. Rest of the steps remain the same.
https://docs.python.org/3.7/library/datetime.html#timedelta-objects
from datetime import date, timedelta
today = date.today()
yesterday = today - timedelta(days = 1)
print(today)
print(yesterday)
Output:
2019-06-14
2019-06-13
>>> import datetime
>>> datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime("%F")
'2015-05-26'