List of string to float

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • puns
    New Member
    • Feb 2011
    • 2

    List of string to float

    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,
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    This is not intended to be the minimum line of ffastest code, but it's a start. How would you do it?

    Code:
    import time
    
    def timeconv(s):
        if "." in s:
            s = s[:s.index(".")]
        return time.strptime(s, "%Y-%m-%d %H:%M:%S")
    
    def convdata(s):
        for f in (float, timeconv):
            try:
                return f(s)
            except:
                pass
        return s
    
    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']
    
    data1 = [convdata(s) for s in data]

    Comment

    • puns
      New Member
      • Feb 2011
      • 2

      #3
      At the moment I'm using exactly same approach as yours bvdet.

      Thanks,

      Comment

      Working...