转换日期时间。日期时间strftime Python的列表列表中的项

2024-09-19 21:01:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表,如下所示:

[['Test', datetime.datetime(2017, 6, 30, 0, 39, 32), 'Log cribs holding approach fills are spreading (failing).  Hole in town approach at end of deck as a result.  Ballast walls independent of girders...could weld them.'], ['Test', datetime.datetime(2017, 6, 29, 23, 12, 3), '3x1 WBC. Town side sill looks as if it shifted towards stream. Stringers overhang sill 2m. Stringers and sills cedar. 70cm of gravel surface. Both sills have been severely scoured, and actively moving. Recommend rebuilding WBC. Stream grade 13%']]

我想把日期时间。日期时间使用以下代码将项目发送到strftime和am:

^{pr2}$

我得到以下错误:

AttributeError: 'str' object has no attribute 'strftime'

当我打印类型(I[1])时,我得到:

<type 'datetime.datetime'>

所以我的问题是,在append语句中,它为什么要将它作为字符串读取?有没有一种方法可以做我想做的事?在


Tags: andoftestlog列表datetimeas时间
1条回答
网友
1楼 · 发布于 2024-09-19 21:01:22

答案是迭代的,而不是附加到列表中:

for i in lst:
    print lst
    lst.append(i[1].strftime('%Y-%b-%d'))

产量:

^{pr2}$

请注意,它一直在向列表添加新项,而不是转换它们,因此它尝试对'2017-Jun-30'执行相同的操作,但失败了。在

相反,我们要转换它们:

for i in lst:
  print lst
  i[1] = i[1].strftime('%Y-%b-%d')

结果是:

[['Test', datetime.datetime(2017, 6, 30, 0, 39, 32), '...'], ['Test', datetime.datetime(2017, 6, 29, 23, 12, 3), '...']]
[['Test', '2017-Jun-30', '...'], ['Test', datetime.datetime(2017, 6, 29, 23, 12, 3), '...']]
[['Test', '2017-Jun-30', '...'], ['Test', '2017-Jun-29', '...']]

相关问题 更多 >