1
lista = [datetimeobject,'test',32]

如果列表中的任何元素是日期时间对象,我需要转换为日期格式(即;2012-01-01)并环绕引号“'”即;'2012-01-01'

我怎样才能实现它?

4

3 回答 3

4

你可以使用repr(str())

In [17]: x=datetime.date(2012,2,5)

In [18]: str(x)              # actually returns repr(str(x)) in interactive prompt
Out[18]: '2012-02-05'

In [22]: print str(x)        # doesn't adds ''
2012-02-05

In [23]: print repr(str(x))  # get '' around solution
'2012-02-05'

对象datetime.datetime

In [31]: str(y)
Out[31]: '2012-02-05 00:00:00'

In [32]: print repr(str(y)[:10])
'2012-02-05'
于 2012-10-19T18:05:43.343 回答
4
from datetime import datetime

convert_date = lambda dt: dt.strftime("'%Y-%m-%d'") if isinstance(dt, datetime) else dt
lista = [datetime.now(), 'test', 32]
map(convert_date, lista)

回报:

["'2012-10-19'", 'test', 32]
于 2012-10-19T18:06:11.850 回答
2
import datetime
found_datetimes = []
DATE_FORMAT = "%Y-%m-%d"

for item in lista:
    if isinstance(item, datetime.datetime):
        found_datetimes.append(datetime.datetime.strftime(item, DATE_FORMAT))

print found_datetimes
于 2012-10-19T18:05:23.073 回答