作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 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/
我是一名优秀的程序员,十分优秀!