【问题标题】:Adding and subtracting seconds column from timestamp column pandas从时间戳列 pandas 中添加和减去秒列
【发布时间】:2021-10-18 14:57:31
【问题描述】:
import pandas as pd
import numpy as np 
example=[["11/19/20","9:40:28","9:40:00:0","00:00:00.2","101"],
     ["12/22/20","9:29:28","9:29:28:15", "00:10:28.0","102"],
     ["2/17/21","9:20:20","9:20:20:2","0:00:05.2","206"]]

example_table= pd.DataFrame(example,columns=["Date","Start_Time","timestamp","Seconds","ID"])

desired_info=[["11/19/20","9:40:28","9:40:00:0","00:00:00.2","101", "9:40:00:2"],
     ["12/22/20","9:29:28","9:29:28:15", "00:10:28.0","102", "9:40:56:15"],
     ["2/17/21","9:20:20","9:20:20:2","0:00:05.2","206","9:20:25:4"]]

desired_table= pd.DataFrame(desired_info,columns=["Date","Start_Time","timestamp","Seconds", "CID","Finish_Time"])

# I can convert one of my time columns 
example_table.Seconds=example_table.Seconds.apply(pd.to_timedelta)
example_table.Seconds=example_table.Seconds.dt.total_seconds()
example_table['Start_Time']=pd.to_datetime(example_table['Start_Time'], format= '%H:%M:%S').dt.time

最终,我希望能够将包含毫秒的秒列添加到时间戳列。

当我尝试以下操作时:

example_table["Finish"]=example_table['timestamp']+example_table['Seconds']

# I get the error: 
# can only concatenate str (not "float") to str

由于我越来越绝望,所以我想,也许我可以在计算中使用 Start_Time。

# if I try with the Start_Time column:
["Finish"]=example_table['Start_Time']+example_table['Seconds']

# unsupported operand type(s) for +: 'datetime.time' and 'float'

所以接下来我尝试使用不同的策略转换时间戳列。 ```# 当我尝试转换时间戳列时,我会根据策略得到许多不同的错误

pd.to_timedelta(example_table.timestamp, unit='ms')
#Error: unit must not be specified if the input contains a str
pd.to_timedelta(example_table.timestamp)
#Error: expected hh:mm:ss format```

最终,我将使用 Finish Time,这实际上是我在另一个实验中的偏移时间,以查找此处显示的其他信息,Find a subset of columns based on another dataframe?

【问题讨论】:

  • “Start_Time”列和“timestamp”列有什么区别?
  • 时间戳包含毫秒,而开始时间只是 hh:mm:ss。我的设备两次都收集了,所以它们也包括在内。

标签: python pandas datetime timestamp


【解决方案1】:

首先你需要创建一个合适的日期时间对象。

df = example_table

df['desired_date'] = pd.to_datetime(df['Date'] + ' ' 
                     + df['timestamp'],format='%m/%d/%y %H:%M:%S:%f')

然后将Seconds 列转换为 timesdelta 并将其添加到所需的日期。

我们必须添加一些格式来获取您的目标字符串格式。

df['desired_date'] =  (
 df['desired_date'] 
 + 
 pd.to_timedelta(df['Seconds'])
 ).dt.strftime('%H:%M:%S:%f').str.rstrip('0')


print(df)

       Date Start_Time   timestamp     Seconds   ID desired_date
0  11/19/20    9:40:28   9:40:00:0  00:00:00.2  101   09:40:00:2
1  12/22/20    9:29:28  9:29:28:15  00:10:28.0  102  09:39:56:15
2   2/17/21    9:20:20   9:20:20:2   0:00:05.2  206   09:20:25:4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-07
    • 2021-12-24
    • 2018-03-04
    • 2015-12-22
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    相关资源
    最近更新 更多