这是我的代码:

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这样的简单约会?


当前回答

也许最短的解决方案是:

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

或甚至更短,例如:

f'{AnyDate}'[:10]

PS:不需要今天。

其他回答

# convert date time to regular format.

d_date = datetime.datetime.now()
reg_format_date = d_date.strftime("%Y-%m-%d %I:%M:%S %p")
print(reg_format_date)

# some other date formats.
reg_format_date = d_date.strftime("%d %B %Y %I:%M:%S %p")
print(reg_format_date)
reg_format_date = d_date.strftime("%Y-%m-%d %H:%M:%S")
print(reg_format_date)

输出,输出

2016-10-06 01:21:34 PM
06 October 2016 01:21:34 PM
2016-10-06 13:21:34

这更短:

>>> import time
>>> time.strftime("%Y-%m-%d %H:%M")
'2013-11-19 09:38'
import datetime
import time

months = ["Unknown","January","Febuary","Marchh","April","May","June","July","August","September","October","November","December"]
datetimeWrite = (time.strftime("%d-%m-%Y "))
date = time.strftime("%d")
month= time.strftime("%m")
choices = {'01': 'Jan', '02':'Feb','03':'Mar','04':'Apr','05':'May','06': 'Jun','07':'Jul','08':'Aug','09':'Sep','10':'Oct','11':'Nov','12':'Dec'}
result = choices.get(month, 'default')
year = time.strftime("%Y")
Date = date+"-"+result+"-"+year
print Date

通过这种方式,您可以获得如下格式的日期:2017年6月22日

您可以执行以下操作:

mylist.append(str(today))
import datetime
print datetime.datetime.now().strftime("%Y-%m-%d %H:%M")

编辑:

根据Cees的建议,我也开始利用时间:

import time
print time.strftime("%Y-%m-%d %H:%M")