我有一个csv文件,其中包含如下所示的列。我想将日期格式更改为2014-1-10,并将其与新列中的时间相结合。我想在没有熊猫的情况下这样做......
Date |Time
1/10/2014|0:09:31
1/10/2014|0:10:29
结果应如下所示:
Date |Time |DateTime
1/10/2014|0:09:31|2014-1-10 0:09:31
1/10/2014|0:10:29|2014-1-10 0:10:29
我尝试了替换,矩阵[] []等,但到目前为止一切都没有效果。非常感谢你的帮助!!
答案 0 :(得分:1)
最简单的方法是使用PETL:
import petl as etl
import datetime
t = etl.fromcsv('my.csv')
t = etl.addfield(t, 'DateTime',
lambda row: datetime.combine(row[0], row[1]))
etl.tocsv(t, 'mynew.csv')
答案 1 :(得分:0)
仅使用Python内置模块:
import csv
import os
import datetime
inFilePath = "C:\\Temp\\SO\\test.csv"
outFilePath = "C:\\Temp\\SO\\temp.csv"
inFile = open(inFilePath, "r")
outFile = open(outFilePath, "wb")
reader = csv.reader(inFile, delimiter='|')
writer = csv.writer(outFile, delimiter='|', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for row in reader:
if "Date " in row:
writer.writerow(row)
continue
newDate = datetime.datetime.strptime(row[0], '%d/%m/%Y').strftime('%Y-%m-%d')
newCell = newDate + " " + row[1]
row.append(newCell)
writer.writerow(row)
inFile.close()
outFile.close()
os.remove(inFilePath)
os.rename(outFilePath, inFilePath)