首页 > 解决方案 > 将日期时间对象列表转换为字符串

问题描述

我想将日期时间对象列表转换为字符串,但对如何完成此任务感到困惑。

hm=dt.date(2013,1,2)
t=hm.strftime('%m/%d/%Y')
t

这产生:'01/02/2013'

但是,当我将变量更改为日期列表时,它会引发错误。

hm=[dt.date(2013,1,1), dt.date(2013,1,2)]
t=hm.strftime('%m/%d/%Y')
t

错误:list indices must be integers or slices, not datetime.date

我是否需要使用某种for循环来完成此任务?

标签: pythondatetime

解决方案


您需要遍历列表以将每个单独的日期转换为string

>>> t = [d.strftime('%m/%d/%Y') for d in hm]

或者,如果您想要将所有日期转换为由其他一些(假设)string连接的字符串,您也可以这样做:string,

>>> s = ', '.join(t)

推荐阅读