【问题标题】:Converting timestamps from a csv to seconds using python使用python将时间戳从csv转换为秒
【发布时间】:2016-11-10 00:14:08
【问题描述】:

我将传感器数据(加速度计、指南针)保存在 csv 文件中,其时间戳为 hh-mm-ss 格式。我想将时间戳转换为秒以绘制特定秒的罗盘读数。 前任: 我要转换

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

。 . . 这样我就可以用 x 轴上的秒数和 y 轴上的指南针方向来绘制读数。

提前致谢

【问题讨论】:

    标签: python csv pandas matplotlib data-analysis


    【解决方案1】:

    将时间转换为datetime 对象,并使用datetime 对象与初始时间的差来计算秒数。 total_seconds 返回 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]
    

    我假设时间戳的年、月和日都是相同的,因为没有提供它们。

    【讨论】:

      【解决方案2】:

      熊猫解决方案:

      假设您有以下 CSV 文件:

      Time,val
      11-26-32,11
      11-26-33,31
      11-26-34,33
      11-26-35,10
      11-26-39,7
      

      解决方案:

      import pandas as pd
      
      In [225]: filename = r'C:\Temp\.data\a.csv'
      
      In [226]: df = pd.read_csv(filename)
      
      In [227]: df
      Out[227]:
             Time  val
      0  11-26-32   11
      1  11-26-33   31
      2  11-26-34   33
      3  11-26-35   10
      4  11-26-39    7
      
      In [228]: df.Time = pd.to_datetime(df.Time, format='%H-%M-%S')
      
      In [229]: df['sec'] = (df.Time - df.ix[0, 'Time']).dt.seconds
      
      In [230]: df
      Out[230]:
                       Time  val  sec
      0 1900-01-01 11:26:32   11    0
      1 1900-01-01 11:26:33   31    1
      2 1900-01-01 11:26:34   33    2
      3 1900-01-01 11:26:35   10    3
      4 1900-01-01 11:26:39    7    7
      

      现在让我们绘制它:

      In [235]: df.set_index('sec').plot()
      Out[235]: <matplotlib.axes._subplots.AxesSubplot at 0x808e2b0>
      

      【讨论】:

        猜你喜欢
        • 2016-03-04
        • 2016-03-04
        • 2013-03-09
        • 2014-11-27
        • 2017-10-24
        • 1970-01-01
        • 2021-12-11
        相关资源
        最近更新 更多