1

I have a csv file, contain datetime, number1, number2, number3 number4.

I use code to read, but how to change the types.

my code:

import csv
import datetime
myarray=([])
filename='Contract.csv'
f=csv.reader(open(filename,'rb'), delimiter=',')
for row in f:
    myarray=array([row for row in f])
print myarray

I get the array looks like: [['2010-05-01 15:20:12 0000' '345' '234' '163' '120'], ['2010-05-02 15:22:12 0000' '335' '214' '164' '120'], ... ]

I have no idea how to change the first column into datetime and the others into float. Please help. Thanks

William
  • 11
  • 1

2 Answers2

1

First, read this question.

Having said that. I use a function like this one (requries python-dateutil) to manage dates too:

from dateutil.parser import parse as date_parser
def _cast_value(self, value):
    tests = (
        int,
        float,
        lambda value: date_parser(value)
    )
    for test in tests:
        try:
            return test(value)
        except ValueError:
            continue
    return value

dateutil will handle different kind of date formats for you.

Community
  • 1
  • 1
tutuca
  • 3,444
  • 6
  • 32
  • 54
0

You need to convert the values:

i=int(s)
dt=datetime.datetime.strptime(s, '%Y-%m-%d ...')
guettli
  • 25,042
  • 81
  • 346
  • 663