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

标签 python csv

我是 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/

相关文章:

python - 将变量写入CSV行python

c# - 使用 CsvHelper 将 CSV 中的所有值读入列表

Python:如何创建用于字符串匹配的查找表

python - 在 python 中发送命令行命令并打印 stdout 和 stderr 的最简单和最可靠的方法是什么?

python - 在 Python 中使用 Selenium,有没有办法在登录在线帐户时使网络驱动程序/浏览器成为 "recognized device"?

python - 是否可以使用openpyxl更改列宽?

当客户端需要数据时,Python 套接字在 socket.recv() 上保持阻塞状态

python - 为什么我不能为 csv.Reader 重复 'for' 循环?

sql-server - 在 SSIS 导出中自动转义引号

c# - 将 double 值导出到 CSV