Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 376
Pyderman Avatar asked Sep 09 '15 23:09

Pyderman


People also ask

How do I get the current date in YYYY-MM-DD in Python?

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.


2 Answers

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' 
like image 174
diegueus9 Avatar answered Sep 20 '22 07:09

diegueus9


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' 
like image 27
kmonsoor Avatar answered Sep 20 '22 07:09

kmonsoor