Search code examples
pythoncsvpandasmatplotlibdata-analysis

Converting timestamps from a csv to seconds using python


I have sensor data(acclerometer,compass) saved in a csv file with their time stamps hh-mm-ss format. I wanted to convert the time stamp into seconds to plot the compass reading at a particular second. ex: I want to convert

11-26-32 -> 0 sec
11-26-33 -> 1 sec
11-26-34 -> 2 sec

. . . so that i can plot the readings with the seconds on x axis and the compass orientations on y axis.

Thanks in advance


Solution

  • Convert the times to datetime objects and use the difference of the datetime objects from the initial time to find the number of seconds. total_seconds returns the number of seconds for the timedelta:

    from datetime import datetime as dt
    
    times = ['11-26-32', '11-26-33', '11-26-34']
    time_format = '%H-%M-%S'
    
    base_time = dt.strptime(times[0], time_format)
    seconds  = [(dt.strptime(t, time_format)- base_time).total_seconds() for t in times]
    print(seconds)
    # [0.0, 1.0, 2.0]
    

    I assume the years, months and days of the timestamps are all the same since they were not provided.