python - 更改 CSV 列中的数据格式

标签 python python-3.x

我正在尝试将 CSV 文件中的日期格式 (DD-MMM-YY) 更改为 (YYYY-MM-DD)。

它抛出错误。

import csv
from datetime import datetime

f1 = open ("D:\\bio.csv","r") # open input file for reading

with open('D:\\mm.csv', 'wb') as f: # output csv file
    writer = csv.writer(f)
    with open('D:\\bio.csv','r') as csvfile: # input csv file
        reader = csv.reader(csvfile, delimiter=',')
        next(reader, None)
        for row in reader:
            dater = row[2]
            #print (dater)
            my_date = datetime.strptime(dater, '%d-%b-%Y')

            kr = (my_date.date())

            row[2] = kr


            data = [["Symbol","Series","Date","Prev Close","Open Price","High Price","Low Price","Last Price","Close Price","Average Price","Total Traded Quantity","Turnover","No. of Trades","Deliverable Qty","% Dly Qt to Traded Qty"],row]

            writer.writerow(data)

f1.close()

示例 CSV

Symbol,Series,Date,Prev Close,Open Price,High Price,Low Price,Last Price,Close Price,Average Price,Total Traded Quantity,Turnover,No. of Trades,Deliverable Qty,% Dly Qt to Traded Qty
BIOCON,EQ,21-Jul-17,402.6,403,409.55,393.2,399,400.25,401.52,3032146,1217472594,39314,321923,10.62
BIOCON,EQ,24-Jul-17,400.25,399,405.9,396.1,399.6,399,401.25,2090835,838941962.6,25520,392951,18.79

一次又一次尝试以多种方式获取输出,最终都会出现相同的错误。

错误:

Traceback (most recent call last):
  File "C:/Users/admin/PycharmProjects/P1/n.py", line 23, in <module>
    writer.writerow(data)
TypeError: a bytes-like object is required, not 'str'

最佳答案

这应该有帮助。

import csv
from datetime import datetime

with open(filename, "rU") as infile, open(filename2, "wb") as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile)
    writer.writerow(next(reader))   #Write Header
    result = []
    for line in reader:        #Iterate each line 
        temp = line
        temp[2] = datetime.strptime(temp[2], '%d-%b-%y').strftime("%Y-%m-%d")    #Update date format
        writer.writerow(temp)   #Write file

输出:

Symbol,Series,Date,Prev Close,Open Price,High Price,Low Price,Last Price,Close Price,Average Price,Total Traded Quantity,Turnover,No. of Trades,Deliverable Qty,% Dly Qt to Traded Qty
BIOCON,EQ,2017-07-21,402.6,403,409.55,393.2,399,400.25,401.52,3032146,1217472594,39314,321923,10.62
BIOCON,EQ,2017-07-24,400.25,399,405.9,396.1,399.6,399,401.25,2090835,838941962.6,25520,392951,18.79

关于python - 更改 CSV 列中的数据格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51640123/

相关文章:

python - 阿尔法中的贝塔 贝塔搜索

Python 2.7 - 打印由给定层数的字母组成的金字塔

python - theano 扫描函数缺少输入错误

python - 在 Python 类型中声明元组的长度

python - 多字符串列映射和清理

python - 如何将字典中的所有列表数字转为零

python - 在Python中读取SPSS(.sav)文件时出现 "title already used as a name or title"错误

python - 快速 API - 如何在 GET 中显示来自 POST 的图像?

python-3.x - 尽管编译成功,f2py 仍未正确导入

python - 如何在布局中间插入 QWidgets?