[Tutor] Datetime Integer Array

Emile van Sebille emile at fenx.com
Tue May 22 00:07:45 CEST 2012


On 5/21/2012 1:04 PM Jeremy Traurig said...
> Hello,
>
> I am reading a data file with a string time stamp as the first column,
> example below:
>
> '03/10/2010 02:00:00'
> '03/10/2010 02:10:00'
> '03/10/2010 02:20:00'
> '03/10/2010 02:30:00'
> etc to n number of rows.
>
> I'm using the numpy function genfromtxt to read this data:
>
> import numpy as np
> datetime_IN = np.genfromtxt('SIL633_original.txt', delimiter='\t',
> skip_header=141, dtype='|S19',
> 		usecols=0)
>
> Now I have a variable called datetime_IN which is an array of datetime
> strings to the nth row. I'd like to convert this strings to a numpy
> array of integers where each column represents a value of time.
> For example, using the same values above, i want an array of integers
> to look like this:
>
> 3,10,2010,2,0,0
> 3,10,2010,2,10,0
> 3,10,2010,2,20,0
> 3,10,2010,2,30,0
> etc to n number of rows.


Using only builtin python functions you can do this as follows:

 >>> source = ['03/10/2010 02:00:00',
... '03/10/2010 02:10:00',
... '03/10/2010 02:20:00',
... '03/10/2010 02:30:00']
 >>>
 >>> for ts in source:
...     print ts, [ int(ii) for ii in 
ts.replace("/","").replace(":","").split() ]
...
03/10/2010 02:00:00 [3, 10, 2010, 2, 0, 0]
03/10/2010 02:10:00 [3, 10, 2010, 2, 10, 0]
03/10/2010 02:20:00 [3, 10, 2010, 2, 20, 0]
03/10/2010 02:30:00 [3, 10, 2010, 2, 30, 0]

HTH,

Emile



More information about the Tutor mailing list