HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCriticalCanonical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
yyyytodaydategettingpython

Problem

Is there a nicer way than the following to return today's date in the YYYY-MM-DD format?

str(datetime.datetime.today()).split()[0]

Solution

Use strftime:

>>> from datetime import datetime
>>> datetime.today().strftime('%Y-%m-%d')
'2021-01-26'


To also include a zero-padded Hour:Minute:Second at the end:

>>> datetime.today().strftime('%Y-%m-%d %H:%M:%S')
'2021-01-26 16:50:03'


To get the UTC date and time:

>>> datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
'2021-01-27 00:50:03'

Code Snippets

>>> from datetime import datetime
>>> datetime.today().strftime('%Y-%m-%d')
'2021-01-26'
>>> datetime.today().strftime('%Y-%m-%d %H:%M:%S')
'2021-01-26 16:50:03'
>>> datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
'2021-01-27 00:50:03'

Context

Stack Overflow Q#32490629, score: 1757

Revisions (0)

No revisions yet.