How can I change date format in csv in Python 3

10,469

Suppose you have a date x:

x = "2017-07-01T15:55Z"

You can convert it into a datetime.datetime with your formate %Y-%m-%dT%H:%MZ:

from datetime import datetime
d = datetime.strptime(x, '%Y-%m-%dT%H:%MZ')

Then format it:

d.strftime("%m/%d/%Y")

You'll get:

'07/01/2017'

The complete code is:

from datetime import datetime
x = "2017-07-01T15:55Z"
x = datetime.strptime(x, '%Y-%m-%dT%H:%MZ').strftime("%m/%d/%Y")

======= EDIT =======

For your follow up question: you need to change row after formatting ts:

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)
Share:
10,469

Related videos on Youtube

Brian Howe
Author by

Brian Howe

Updated on June 04, 2022

Comments

  • Brian Howe
    Brian Howe almost 2 years

    I'm new to Python, and I have a set of data in a CSV file that I would like to change the format from

    '%Y-%m-%dT%H:%MZ' to '%m/%d/%Y'

    I'm running Python 3 on Windows. I've searched S.O. (and other sites) several times but none of the examples/solutions seem to actually convert the format of the output. I've read the Python online documentation but was unable to take anything meaningful away from it.

    Here's the code I just tried, and it doesn't change the formatting on any of the entries in the column:

    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()
    

    I get no errors, but I get no change in the format of the timestamp either.

  • Brian Howe
    Brian Howe over 6 years
    I tried your example with no results. I am doing something wrong, but I do not know what (see code snippet above).
  • Huang
    Huang over 6 years
    @BrianHowe you changed ts but not row. See my answer. Hope it works now.
  • Brian Howe
    Brian Howe over 6 years
    Thank you. That one line was what was missing. Again, thank you.