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?
strftime() Function to Format Date to YYYYMMDD in Python. The strftime() is used to convert a datetime object to a string with a given format. We can specify the format for YYYY-MM-DD in the function as %Y-%m-%d . Note that this function returns the date as a string.
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 date today = str(date.today()) print(today) # '2017-12-26'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With