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

2019-01-16 02:38发布

问题:

I'm using:

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

to return today's date in the form YYYY-MM-DD.

Is there a less crude way to achieve this?

回答1:

You can use strftime:

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


回答2:

There's even simpler way than the accepted answer; valid both for Python 2 & 3.

from datetime import date
today = str(date.today())
print(today)   # '2017-12-26'


回答3:

Datetime is just lovely if you like remembering funny codes. Wouldn't you prefer simplicity?

>>> import arrow
>>> arrow.now().format('YYYY-MM-DD')
'2017-02-17'

This module is clever enough to understand what you mean.

Just do pip install arrow.



回答4:

I always use the isoformat() function 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 standard format as well.

from datetime import datetime
now = datetime.today().isoformat()
print(now) # '2018-12-05T11:15:55.126382'


回答5:

I prefer this. (because this is simple. but maybe somehow inefficient and buggy. You must check the exit code of shell command if you want very strongly error-proof program.)

os.system('date +%Y-%m-%d')