[Tutor] Datetime Integer Array

Andreas Perstinger andipersti at gmail.com
Tue May 22 20:01:42 CEST 2012


On Mon, 21 May 2012 13:04:26 -0700 
Jeremy Traurig <jeremy.traurig at gmail.com> wrote:
> I have already tried creating a numpy array of integers using this
> code:
> 
> import time
> time_format = %m/%d/%Y %H:%M:%S
> for x in range(len(datetime_IN)):
>     junk = time.strptime(datetime[x],time_format)
>     junk2 = [y for y in junk]
> 
> The above code works in general

No, this code doesn't work at all because there are two errors in it
(syntax error in line 2 and name error in line 4). So in the future
please copy&paste your code and don't retype it.

> the same number of rows as datetime_IN, and I understand it doesn't
> because the previous data in junk2 is lost. I'd like to build the
> junk2 array but I'm not sure how.

Currently, as you've noticed, you overwrite junk2 with each iteration.
You need to append junk2 (which represents one row) to an array:

import time
time_format = "%m/%d/%Y %H:%M:%S"
datetime_IN = ['03/10/2010 02:00:00', 
               '03/10/2010 02:10:00',
               '03/10/2010 02:20:00', 
               '03/10/2010 02:30:00']
datetime_NEW = []
for d in datetime_IN:
    junk = time.strptime(d, time_format)
    junk2 = [y for y in junk]
    datetime_NEW.append(junk2)

You will notice that there is more information than you want in each
row and the items are not in the order you've specified. So you
probably want to construct each row manually in the order you need:

datetime_NEW = []
for d in datetime_IN:
    d = time.strptime(d, time_format)
    datetime_NEW.append([d.tm_mon, d.tm_mday, d.tm_year,
                         d.tm_hour, d.tm_min, d.tm_sec])

HTH, Andreas


More information about the Tutor mailing list