Getting today's date in YYYY-MM-DD in Python?
You can use strftime:
>>> from datetime import datetime>>> datetime.today().strftime('%Y-%m-%d')'2021-01-26'
Additionally, for anyone also looking for a zero-padded Hour, Minute, and Second at the end: (Comment by Gabriel Staples)
>>> datetime.today().strftime('%Y-%m-%d-%H:%M:%S')'2021-01-26-16:50:03'
You can use datetime.date.today()
and convert the resulting datetime.date
object to a string:
from datetime import datetoday = str(date.today())print(today) # '2017-12-26'
I always use the isoformat()
method for this.
from datetime import date today = date.today().isoformat()print(today) # '2018-12-05'
Note that this also works on datetime
objects if you need the time in the standard ISO 8601 format as well.
from datetime import datetimenow = datetime.today().isoformat()print(now) # '2018-12-05T11:15:55.126382'