繁体   English   中英

Python3-格式化列表中的日期

[英]Python3 - Format Date in List

我目前正在尝试将日期(“ 2017-01-25T09:00”)转换为%Y-%m-%d%H:%M

我尝试使用strptime()但收到TypeError:strptime()参数1必须为str,而不是list

我需要在列表中的每个项目上尝试一下吗? 在列表中,日期显示了更多的感谢。

代码步骤:

  1. 从JSON中的Rest请求获取响应
  2. 提取标题值
  3. 逐行提取主体
  4. 使用不正确的日期格式将值更新为所需的格式
  5. 将每个提取的行写入电子表格

这是我目前正在尝试的:

    for line in body:
    #newMessageDate = line.get('messagedate')
    if line:
        date_formats = ["%Y-%m-%d%T%H:%M"]
        for date_fmt in date_formats:
            try:
                line = datetime.datetime.strptime(line, date_fmt).strftime('%Y-%m-%d %H:%M')
            except ValueError:
                continue
            else:
                break

输出的csv文件的精简版本如下:

driver,id,startdate,startlocation,finsihlocation,finsihtime
Driver 1,3,2016-09-21T12:02,Dublin,2016-09-21T15:02
Driver 2,4,2016-09-21T12:02,Dublin,2016-09-21T15:02

提前致谢!

似乎您正在使用DictReader从CSV文件DictReader 这意味着该line是在当前行中保存键及其值的字典,如当前注释行#newMessageDate = line.get('messagedate')

在这种情况下,您应该使用line.get('messagedate')而不是line本身。

newMessageDate = line.get('messagedate')
newMessageDate = datetime.datetime.strptime(newMessageDate, date_fmt).strftime('%Y-%m-%d %H:%M')

(我跳过了循环和try/except因为它们没有改变。)


不幸的是,您没有说明line外观。 从最新评论看,您似乎不是读CSV而是读JSON,并且该linelist而不是dict 在这种情况下,您必须使用相应的索引访问date元素,例如newMessageDate = line[3] (假设日期在列表的第四位)。 其余答案仍然成立。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM