这是我的代码:

import datetime
today = datetime.date.today()
print(today)

这张照片是:2008-11-22,这正是我想要的。

但是,我有一个列表,我要将其附加到列表中,然后突然一切都变得“不稳定”。代码如下:

import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print(mylist)

这将打印以下内容:

[datetime.date(2008, 11, 22)]

我怎样才能得到像2008-11-22这样的简单约会?


当前回答

以下是如何将日期显示为(年/月/日):

from datetime import datetime
now = datetime.now()

print '%s/%s/%s' % (now.year, now.month, now.day)

其他回答

也许最短的解决方案是:

mylist.append(str(AnyDate)[:10])

或甚至更短,例如:

f'{AnyDate}'[:10]

PS:不需要今天。

from datetime import date

def today_in_str_format():
    return str(date.today())

print (today_in_str_format())

这将打印2018-06-23,如果这是你想要的:)

对于pandas.Timestamps,可以使用strftime(),例如:

utc_now = datetime.now()

对于isoformat:

utc_now.isoformat()

对于任何格式,例如:

utc_now.strftime("%m/%d/%Y, %H:%M:%S")

您可以执行以下操作:

mylist.append(str(today))

使用date.strftime。文档中描述了格式参数。

这是你想要的:

some_date.strftime('%Y-%m-%d')

这一次考虑了Locale。(这样做)

some_date.strftime('%c')