Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change date format in csv in Python 3

Tags:

python

csv

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.

like image 995
Brian Howe Avatar asked Mar 03 '26 16:03

Brian Howe


1 Answers

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)
like image 179
Huang Avatar answered Mar 05 '26 06:03

Huang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!