'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 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!
Solution 1:[1]
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 2:[2]
>>> import datetime
>>> datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime("%F")
'2015-05-26'
Solution 3:[3]
Calling .isoformat() on a date object will give you YYYY-MM-DD
from datetime import date, timedelta
(date.today() - timedelta(1)).isoformat()
Solution 4:[4]
I'm trying to use only import datetime based on this answer.
import datetime
oneday = datetime.timedelta(days=1)
yesterday = datetime.date.today() - oneday
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Francis Colas |
| Solution 2 | Paul Rubel |
| Solution 3 | Kevin Nasto |
| Solution 4 | M Koetz |
