Getting today's date in YYYY-MM-DD in Python?
I'm using:
str(datetime.datetime.today()).split()[0]
to return today's date in the YYYY-MM-DD
format.
Is there a less crude way to achieve this?
Solution 1:
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'
Solution 2:
You can use datetime.date.today()
and convert the resulting datetime.date
object to a string:
from datetime import date
today = str(date.today())
print(today) # '2017-12-26'
Solution 3:
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 datetime
now = datetime.today().isoformat()
print(now) # '2018-12-05T11:15:55.126382'