2

Source csv:

column a, column b, 2021-01-09, column d
column a, column b, 2021-01-10, column d
column a, column b, 2021-01-11, column d

Desired output:

09/01/2021, column a, column b, column d
10/01/2021, column a, column b, column d
11/01/2021, column a, column b, column d

What is the best method to achieve this, pythonically?
Thanks in advance!

3 Answers 3

1

Assuming your row from the csv is like

row = ["column a", "column b", "2021-01-09", "column d"]

you can do something like

import datetime

row.sort()
row[0] = datetime.datetime.strptime(row[0], '%Y-%m-%d').strftime('%d/%m/%y')

gives row as

>>> row
['09/01/21', 'column a', 'column b', 'column d']
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Jarvis for your concise answer!
1

One way with pandas to achieve that as you already have answer's using csv.DictWriter

import pandas as pd
df = pd.read_csv('source.csv',names=["ColA", "ColB", "Date", "ColD"])
df['Date'] = pd.to_datetime(df['Date'].str.strip(), format='%Y-%m-%d').dt.strftime('%d/%m/%Y')
new_df = df[['Date', 'ColA', 'ColB', 'ColD']]
print(new_df)

Output:

         Date      ColA       ColB       ColD
0  09/01/2021  column a   column b   column d
1  10/01/2021  column a   column b   column d
2  11/01/2021  column a   column b   column d

1 Comment

glad it helps you somehow :)
0

Reordering, as per:
Python - re-ordering columns in a csv

import csv

with open('file.csv', 'r') as infile, open('reordered.csv', 'a') as outfile:
    fieldnames = ['column c', 'column a', 'column b', 'column d']
    writer = csv.DictWriter(outfile, fieldnames=fieldnames)
    writer.writeheader()
    for row in csv.DictReader(infile):
        writer.writerow(row)
        

Adding dates:
In python how to change date format in a csv?

import datetime

with open("reordered.csv", 'r') as csvfile, open('file.csv', 'w') as temp_file:

    for line in csvfile.readlines():
        # Fetch all dates in the csv
        dates = line.split(',')

        # Extract date, month and year
        yr, mon, dt = dates[0].split('-')

        # Convert the second date and replace
        dates[0] = datetime.datetime.strptime(dates[0], '%y-%b-%d').strftime('%d/%b/%Y')

        # Write date to temp file
        temp_file.write(','.join(dates))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.