首页 > 解决方案 > 以 CSV 格式输出时更改日期格式

问题描述

我正在从日期格式为 YYYY-MM-DD 的数据库中读取数据。但是,当我将其写入 CSV 时,日期会更改为 MM/DD/YYYY。我想阻止这种情况发生。我想添加一行 usingdatetime以强制执行我的首选格式。这是我尝试过的。

# write out
for line in reader:
    # format the date to YYYY-MM-DD (line 26 is date column)
    line[26] = datetime.datetime.strptime(line[26], "%Y-%m-%d")
    # write out 
    csv_out.writerow(line)

但是,我从中得到以下错误:

line[26] = line[26].datetime.strftime("%Y-%m-%d")
AttributeError: 'str' object has no attribute 'datetime'

如何正确格式化日期?

编辑:注意line[26]是 str 格式。

标签: pythoncsvdatetime

解决方案


你试过做line[26] = datetime.datetime.strptime(line[26], "%Y-%m-%d").strftime("%Y-%m-%d")

例如:

line = '2019-05-12'
print(type(line))

>>> <class 'str'>

line = datetime.datetime.strptime(line, "%Y-%m-%d").strftime("%Y-%m-%d")
print(line)

>>> 2019-12-05

推荐阅读