Python 2.7 formatting data for writing as csv
Question: I'm trying to write data into a CSV file. I have data from several sensors and
time/date from a Real Time Clock. The sensor data is fine but I'm going round
in circles with formatting the RTC data. I've tried lots of things and read as
many relevant posts as my ageing brain can handle.

The clock data is in val

    
    
    #print "second =", val[0]
    #print "minute =", val[1]
    #print "hour =", val[2]
    #print "day of week =", val[3]
    #print "day of month =", val[4]
    #print "month =", val[5]
    #print "year =", val[6]
    

So for instance this prints time followed by date.

    
    
    print "RTC Time is ", val[2], ":", val[1], ":", val[0]
    print "RTC Date is ", val[4], "/", val[5], "/", "20",val[6]
    

The closest I've got to what I actually want is.

    
    
       import csv
    
       datetime = val[6],val[5],val[4],val[2],val[1],val[0]
    
       filecsv = open('tidelog.csv', 'a+') #writing to csv log file
       writer = csv.writer(filecsv,dialect='excel')
       stuff = [datetime, temp_inside, humidity, press, response]
       writer.writerow(stuff)
       filecsv.close()
    

The output csv looks like this

    
    
    "(14, 3, 28, 15, 52, 37)",29,47,1005,2208
    

The date/time yy mm dd hh mm ss is inside the quotes

What I'm trying to get is the date time with hyphen separators in the first
column like below.

    
    
    14-3-28-15-52-37,29,47,1005,2208
    

Any help would be appreciated

Derek


Answer: You can use `join` with a hyphen like so:

    
    
    >>> val
    [37, 52, 15, 4, 28, 3, 14]
    >>> '-'.join(str(x) for x in [val[6],val[5],val[4],val[2],val[1],val[0]])
    '14-3-28-15-52-37'
    

Your method does not work because you are implicitly creating a tuple:

    
    
    >>> 1,2,3
    (1, 2, 3)
    >>> val[6],val[5],val[4],val[2],val[1],val[0]
    (14, 3, 28, 15, 52, 37)
    

* * *

_Edit_

As stated in the comments, you can use
[reversed](http://docs.python.org/2.7/library/functions.html#reversed) on your
list rather than index by index:

    
    
    >>> list(reversed([1,2,3,4,5]))
    [5, 4, 3, 2, 1]
    

