用Python来表示yyyyy - mm - dd的日期?

时间:2023-01-14 14:23:58

I'm using:

我用的是:

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

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

以YYYY-MM-DD格式返回今天的日期。

Is there a less crude way to achieve this?

有没有更简单的方法来实现这一点?

4 个解决方案

#1


135  

You can use strftime:

您可以使用strftime:

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

#2


22  

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

如果你喜欢记住有趣的代码,Datetime很可爱。难道你喜欢简单?

>>> 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.

只需执行pip安装箭头。

#3


10  

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

甚至比公认的答案更简单;对Python 2和3都有效。

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

#4


2  

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

我更喜欢这个。(因为这是简单的。但是可能有些效率低下,而且有漏洞。如果需要非常强的错误验证程序,则必须检查shell命令的退出代码。

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

#1


135  

You can use strftime:

您可以使用strftime:

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

#2


22  

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

如果你喜欢记住有趣的代码,Datetime很可爱。难道你喜欢简单?

>>> 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.

只需执行pip安装箭头。

#3


10  

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

甚至比公认的答案更简单;对Python 2和3都有效。

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

#4


2  

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

我更喜欢这个。(因为这是简单的。但是可能有些效率低下,而且有漏洞。如果需要非常强的错误验证程序,则必须检查shell命令的退出代码。

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