Getting today's date in YYYY-MM-DD in Python?

Pyderman picture Pyderman · Sep 10, 2015 · Viewed 536.6k times · Source

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?

Answer

diegueus9 picture diegueus9 · Sep 10, 2015

You can use strftime:

from datetime import datetime

datetime.today().strftime('%Y-%m-%d')

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')