python - 以 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 格式。
解决方案
你试过做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
推荐阅读
- plugins - 在 tawk.to 上唱歌给了我访问被拒绝的错误
- java - GWT 不编译项目 nocache.js 警告
- java - java代码抽象,泛型,这里的泛型java代码看不懂
- python - Django REST Framework - Django 在`pip3 list` 中大写
- postgresql - 从 SQL 查询中删除内部联接
- javascript - 在单页应用程序中应用 div(卡片)中的排序方法 - Vanilla Javascript
- javascript - 表示函数上下文的变量?
- html - 创建具有清晰文本元素的固定、较暗、模糊的背景图像
- installation - 在 MacOS Big Sur(M1 芯片)上安装自制软件时收到警告
- mysql - 我们如何分别展示不同类型的产品?