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?
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?
You can use strftime:
datetime.datetime.today().strftime('%Y-%m-%d')
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'
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
.
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'
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')