0

I have seen this question asked on Stack Overflow multiple times before, however, what I have not seen is anyone either ask nor answer the question properly here. So, here is my question: I have a .csv file named selected.csv, with three columns - Date (LT), AQI and Raw Conc. The date is in the format dd-mm-yyyy hh:mm. I want to convert the format of the date to yyyy-mm-dd, thereafter, saving the corrected data with three columns - Date, AQI and Raw Conc. as corrected.csv. I have tried the code typed below, but to no avail.

import csv
from datetime import datetime

output_file = open(r"C:\Users\Win-8.1\Desktop\delhi\corrected.csv", "wb")
fieldnames = ['Date', 'AQI' , 'Raw Conc.']
writer = csv.DictWriter(output_file, fieldnames = fieldnames)
writer.writeheader()

with open(r"C:\Users\Win-8.1\Desktop\delhi\selected.csv") as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        output_row = {}
        output_row['Date'] = datetime.datetime.strptime(row['Date (LT)'], '%d-%m-%Y %H:%M').strftime('%Y-%m-%d')
        output_row['AQI'] = row['AQI']
        output_row['Raw Conc.'] = row['Raw Conc.']
        writer.writerow(output_row)

output_file.close()
  • Possible duplicate of [How to convert a date string to different format](https://stackoverflow.com/questions/14524322/how-to-convert-a-date-string-to-different-format) –  Nov 24 '17 at 20:26
  • This question has been worded differently and asked before multiple times, however, all of them seem to suggest that datetime.datetime.strptime(string, 'old format').strptime('new format') as the solution, which is not working in the code above. – Swagamachari Nov 28 '17 at 08:56

1 Answers1

0
output_row['Date'] = datetime.strptime(row['Date (LT)'], '%d-%m-%Y %H:%M').strftime('%Y-%m-%d')

You are using also %H:%M when you mentioned the format is DD-MM-YYYY. Maybe you didn't intend this?