如何从固定时间减去pandas datetime列?

 收藏

我有一个数据框列,其值的范围从12:00到00:00(分钟:秒格式),并且我试图从固定时间12:00(分钟:秒格式)减去该列的值。我创建了一个变量:

 twelve_mins = pd.to_datetime('12:00', format='%M:%S')

当我尝试创建列“ remaining_time”时,出现错误:

unsupported operand type(s) for -: 'Timestamp' and 'datetime.time'

我该怎么做才能找到“ remaining_time”值?我要从中减去的列已准备好采用datetime形式:

pbp['time_left_in_period'] = pd.to_datetime(pbp['time_left_in_period'], format='%M:%S').dt.time

这是我的数据的玩具选择:

idx   time_left_in_period
0     00:11:44
1     00:11:44
2     00:11:27
3     00:11:27
4     00:11:23
5     00:11:21
6     00:11:18
7     00:11:02
8     00:10:59
9     00:10:51
10    00:10:51
11    00:10:51
12    00:10:48
13    00:10:48
14    00:10:32
15    00:10:32
16    00:10:21
17    00:10:21
18    00:10:05
19    00:09:56
回复
  • 您可以使用datetime.timedelta()

    pbp['time_left_in_period'] = pbp['time_left_in_period'].apply(pd.to_timedelta)
    pbp['remaining_time'] = pbp['time_left_in_period'].apply(lambda x: datetime.timedelta(minutes=12) - x)
    

    结果:

        time_left_in_period     remaining_time
    0       00:11:44                00:00:16
    1       00:11:44                00:00:16
    2       00:11:27                00:00:33
    3       00:11:27                00:00:33
    4       00:11:23                00:00:37
    5       00:11:21                00:00:39
    6       00:11:18                00:00:42
    7       00:11:02                00:00:58
    8       00:10:59                00:01:01
    9       00:10:51                00:01:09
    10      00:10:51                00:01:09
    11      00:10:51                00:01:09
    12      00:10:48                00:01:12
    13      00:10:48                00:01:12
    14      00:10:32                00:01:28
    15      00:10:32                00:01:28
    16      00:10:21                00:01:39
    17      00:10:21                00:01:39
    18      00:10:05                00:01:55
    19      00:09:56                00:02:04