【问题标题】:Pandas: How can I add two timestamp values?Pandas:如何添加两个时间戳值?
【发布时间】:2017-08-27 01:45:24
【问题描述】:

我正在尝试添加两个以上的时间戳值,并且希望以分钟/秒为单位看到输出。如何添加两个时间戳?我基本上想做:'1995-07-01 00:00:01' + '1995-07-01 00:05:06',看看total time>=60minutes。 我试过这个代码:df['timestamp'][0]+df['timestamp'][1]。我提到了这个post,但我的时间戳来自数据框。 我的数据框列的标题如下所示:

0   1995-07-01 00:00:01
1   1995-07-01 00:00:06
2   1995-07-01 00:00:09
3   1995-07-01 00:00:09
4   1995-07-01 00:00:09
Name: timestamp, dtype: datetime64[ns]

我收到此错误: TypeError: unsupported operand type(s) for +: 'Timestamp' and 'Timestamp'

【问题讨论】:

  • 您希望如何添加两个时间戳?如果加上周二和周三,那会是周五吗?请显示给定输入的预期输出。
  • 我想添加两个时间戳 '1995-07-01 00:00:01' + '1995-07-01 00:59:59' 看到这样的输出 60 分钟。
  • 好的,所以你想要某种持续时间?从什么时候开始的持续时间?
  • 是的,我有 IP 地址和时间戳的数据框。我想知道每个 IP 地址的总持续时间。我试图通过添加每个唯一 IP 地址的所有时间戳值来计算这一点。
  • 如果您有时间戳,则持续时间始终需要减法。因为持续时间有开始和结束。您正在尝试添加星期二和星期三。

标签: python pandas data-analysis data-science data-cleaning


【解决方案1】:

问题是添加Timestamps 没有意义。如果他们在不同的日子呢?你想要的是Timedeltas 的总和。我们可以通过从整个系列中减去一个共同的日期来创建Timedeltas。让我们减去最短日期。然后总结Timedeltas。让s成为你的Timestamps系列

s.sub(s.dt.date.min()).sum().total_seconds()

34.0

【讨论】:

    【解决方案2】:
    #Adding two timestamps is not supported and not logical
    #Probably, you really want to add the time rather than the timestamp itself
    #This is how to extract the time from the timestamp then summing it up
    
    import datetime
    import time
    
    t = ['1995-07-01 00:00:01','1995-07-01 00:00:06','1995-07-01 00:00:09','1995-07-01 00:00:09','1995-07-01 00:00:09']
    tSum = datetime.timedelta()
    df = pd.DataFrame(t, columns=['timestamp'])
    for i in range(len(df)):
        df['timestamp'][i] = datetime.datetime.strptime(df['timestamp'][i], "%Y-%m-%d %H:%M:%S").time()
        dt=df['timestamp'][i]
        (hr, mi, sec) = (dt.hour, dt.minute, dt.second)
        sum = datetime.timedelta(hours=int(hr), minutes=int(mi),seconds=int(sec))
        tSum += sum
    if tSum.seconds >= 60*60:
        print("more than 1 hour")
    else:
        print("less than 1 hour")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-21
      • 1970-01-01
      • 1970-01-01
      • 2018-03-22
      • 2018-11-17
      • 1970-01-01
      • 1970-01-01
      • 2016-08-06
      相关资源
      最近更新 更多