gpt4 book ai didi

python - 如何在Python 3中更改csv中的日期格式

转载 作者:行者123 更新时间:2023-11-30 22:32:01 25 4
gpt4 key购买 nike

我是 Python 新手,我在 CSV 文件中有一组数据,我想更改其格式

'%Y-%m-%dT%H:%MZ''%m/%d/%Y'

我在 Windows 上运行 Python 3。我搜索过S.O. (和其他网站)多次,但似乎没有一个示例/解决方案真正转换了输出的格式。我已阅读 Python 在线文档,但无法从中获取任何有意义的内容。

这是我刚刚尝试过的代码,它不会更改列中任何条目的格式:

with open('some_file', 'r') as source:
with open('some_other_file', 'w') as result:
writer = csv.writer(result, lineterminator='\n')
reader = csv.reader(source)
source.readline()
for row in reader:
ts = row[17]
ts = datetime.strptime(ts, '%Y-%m-%dT%H:%MZ').strftime("%m/%d/%Y")
if ts != "":
writer.writerow(row)
source.close()
result.close()

我没有收到任何错误,但时间戳的格式也没有发生任何变化。

最佳答案

假设您有一个日期x:

x = "2017-07-01T15:55Z"

您可以使用您的格式 %Y-%m-%dT%H:%MZ 将其转换为 datetime.datetime:

from datetime import datetime
d = datetime.strptime(x, '%Y-%m-%dT%H:%MZ')

然后格式化:

d.strftime("%m/%d/%Y")

你会得到:

'07/01/2017'

完整代码为:

from datetime import datetime
x = "2017-07-01T15:55Z"
x = datetime.strptime(x, '%Y-%m-%dT%H:%MZ').strftime("%m/%d/%Y")

=======编辑=======

对于您的后续问题:您需要在格式化 ts 后更改 row:

ts = row[17]
ts = datetime.strptime(ts, '%Y-%m-%dT%H:%MZ').strftime("%m/%d/%Y")
if ts != "":
row[17] = ts # this is what you miss
writer.writerow(row)

关于python - 如何在Python 3中更改csv中的日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45622279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com