By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,270 Members | 1,703 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,270 IT Pros & Developers. It's quick & easy.

List of string to float

P: 2
Hi,

I'm reading from csv file using csv module and end-up with a list of string (while actual data is time stamp or float)
lst=['2010-02-15 18:22:08.918000', '2010-12-11 00:00:00.000000', '10740.0', '10740.0', '10750.0', '10745.0', '10741.2457045']

How can I convert list to date time and float using minimum line of fastest code. Fastest because csv size are upto 20 MB and have hundreds of them to read from.

Thanks,
Feb 22 '11 #1
Share this Question
Share on Google+
2 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
This is not intended to be the minimum line of ffastest code, but it's a start. How would you do it?

Expand|Select|Wrap|Line Numbers
  1. import time
  2.  
  3. def timeconv(s):
  4.     if "." in s:
  5.         s = s[:s.index(".")]
  6.     return time.strptime(s, "%Y-%m-%d %H:%M:%S")
  7.  
  8. def convdata(s):
  9.     for f in (float, timeconv):
  10.         try:
  11.             return f(s)
  12.         except:
  13.             pass
  14.     return s
  15.  
  16. data = ['2010-02-15 18:22:08.918000', '2010-12-11 00:00:00.000000', '10740.0', '10740.0', '10750.0', '10745.0', '10741.2457045']
  17.  
  18. data1 = [convdata(s) for s in data]
Feb 22 '11 #2

P: 2
At the moment I'm using exactly same approach as yours bvdet.

Thanks,
Feb 23 '11 #3

Post your reply

Sign in to post your reply or Sign up for a free account.