Link to home
Start Free TrialLog in
Avatar of merijn van der leek
merijn van der leek

asked on

csv date from numbers to text

Hee i have this csv which takes dates as 20150731 (meaning 31 july 2015).
I want to print these numbers as 7 aug 1990 so the first three letters of the month.
Does anyone know how to do this?
This is my code so far:

import csv

with open("climate.csv", "r" ) as csvFile:
    reader = csv.DictReader(csvFile)
    max_temp = 0
    min_temp = 0
    for row in reader:
        row_value = int(row['TX'])
        if row_value > max_temp:
            max_temp = row_value
            max_date = int(row['DATE'])
        if row_value < min_temp:
            min_temp = row_value
            min_date = int(row['DATE'])
    

Open in new window


And these are the first lines of the csv:

STAID,SOUID,DATE,TX,Q_TX
162,100522,19010101,-31,0
162,100522,19010102,-13,0
162,100522,19010103,-5,0
162,100522,19010104,-10,0
Avatar of aikimark
aikimark
Flag of United States of America image

import datetime

def ISOstringToDate(strDate):
    return datetime.date(int(strDate[0:4]), 
                         int(strDate[4:6]), 
                         int(strDate[6:8])
                        )

strDate = '19010106'
d = ISOstringToDate(strDate)
print(d.strftime('%d %b %Y'))

Open in new window

Avatar of merijn van der leek
merijn van der leek

ASKER

Hey this worked perfect with 19010106 but when i say strDate = max_temp it doesn't work anymore. Any idea why?
max_temp
what about max_date?
Hey sorry i mean max_date doesn't work. My bad.
This is the error i get btw.
TypeError: 'int' object is not subscriptable
please post your code
Hey this is my code:
import csv
import datetime
with open("climate.csv", "r" ) as csvFile:
    
    reader = csv.DictReader(csvFile)
    max_temp = 0
    min_temp = 0
    for row in reader:
        row_value = int(row['TX'])
        if row_value > max_temp:
            max_temp = row_value
            max_date = int(row['DATE'])
        if row_value < min_temp:
            min_temp = row_value
            min_date = int(row['DATE'])
               
        
    def ISOstringToDate(strDate):
        return datetime.date(int(strDate[0:4]), 
                             int(strDate[4:6]), 
                             int(strDate[6:8])
                            )
    strDate = max_date
    d = ISOstringToDate(strDate)
    print(d.strftime('%d %b %Y'))

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of aikimark
aikimark
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks so much it works!
What does that datetime import do by the way?
brings the library into your project