Jacob Jacob - 1 year ago 167
Python Question

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

As an input to an API request I need to get yesterday's date as a string in the format

. 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!

Answer Source

You Just need to subtract one day from today's date. datetime.timedelta(1) will gieve you a timedelta object which is a duration of one day and is subtractable from datetime object. Then you can use datetime.strftime in orer to convert the date object to string based on your espected format:

>>> from datetime import datetime, timedelta
>>> datetime.strftime(datetime.now() - timedelta(1), '%Y-%m-%d')

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')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download