[Tutor] Convert values in a list back and forth from ints and time

Sander Sweers sander.sweers at gmail.com
Tue Jan 6 01:52:32 CET 2009


Hello Tutors,

I use the csv module to read and write a csv file. When I read the
file into a new list I convert the ints and the dates to int and time
objects so I can do calculations. I use the below function which
works.

def convertValue(value, dateformat, reverse=False):
    if reverse:
        try:
            return strftime(dateformat, value)
        except TypeError:
            return str(value)
    else:
        try:
            return int(float(value))
        except ValueError:
            try:
                return strptime(value, dateformat)
            except:
                return value

When writing the lines back to a csv file I loop over the lists and
convert the values back with the same function but in reverse but....

I was just wondering if there is another way of dealing with this.
Should I pass the strings to the calculation function (not written
yet), do my calculations and have it return strings? Or do you have
another way?

Thanks
Sander


More information about the Tutor mailing list