Python - Get Yesterday's date as a string in YYYY-MM-DD format

PythonPython 2.7Python 3.xDateDatetime

Python Problem Overview


As an input to an API request I need to get yesterday's date as a string in the format YYYY-MM-DD. I have a working version which is:

yesterday = datetime.date.fromordinal(datetime.date.today().toordinal()-1)
report_date = str(yesterday.year) + \
   ('-' if len(str(yesterday.month)) == 2 else '-0') + str(yesterday.month) + \
   ('-' if len(str(yesterday.day)) == 2 else '-0') + str(yesterday.day)

There must be a more elegant way to do this, interested for educational purposes as much as anything else!

Python Solutions


Solution 1 - Python

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:

from datetime import datetime, timedelta


def yesterday(frmt='%Y-%m-%d', string=True):
    yesterday = datetime.now() - timedelta(1)
    if string:
        return yesterday.strftime(frmt)
    return yesterday

example:

In [10]: yesterday()
Out[10]: '2022-05-13'

In [11]: yesterday(string=False)
Out[11]: datetime.datetime(2022, 5, 13, 12, 34, 31, 701270)

Solution 2 - Python

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

Solution 3 - Python

>>> import datetime
>>> datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime("%F")
'2015-05-26'

Solution 4 - Python

Calling .isoformat() on a date object will give you YYYY-MM-DD

from datetime import date, timedelta
(date.today() - timedelta(1)).isoformat()

Solution 5 - Python

I'm trying to use only import datetime based on this answer.

import datetime

oneday = datetime.timedelta(days=1)
yesterday = datetime.date.today() - oneday

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJacobView Question on Stackoverflow
Solution 1 - PythonMazdakView Answer on Stackoverflow
Solution 2 - PythontheRahulModyView Answer on Stackoverflow
Solution 3 - PythonPaul RubelView Answer on Stackoverflow
Solution 4 - PythonKevin NastoView Answer on Stackoverflow
Solution 5 - PythonM KoetzView Answer on Stackoverflow