错误舍入到前15分钟的时间-Python

时间:2019-03-06 03:42:28

标签: python pandas datetime rounding

我已经开发出一种粗略的方法来将时间戳取整到前15分钟。例如,如果时间戳为8:10:00,则将其舍入为8:00:00

但是,当它超过15分钟时,会四舍五入到前一个小时。例如,如果时间戳为8:20:00,出于某种原因将其舍入为7:00:00吗?我将在下面列出两个示例。

正确的舍入:

import pandas as pd
from datetime import datetime, timedelta

d = ({
    'Time' : ['8:00:00'],                                                                                          
     })

df = pd.DataFrame(data=d)

df['Time'] = pd.to_datetime(df['Time'])

FirstTime = df['Time'].iloc[0]

def hour_rounder(t):
    return (t.replace(second=0, microsecond=0, minute=0, hour=t.hour)
               -timedelta(hours=t.minute//15))

StartTime = hour_rounder(FirstTime)
StartTime = datetime.time(StartTime)

print(StartTime)

出局:

08:00:00

不正确的舍入:

import pandas as pd
from datetime import datetime, timedelta

d = ({
    'Time' : ['8:20:00'],                                                                                          
     })

df = pd.DataFrame(data=d)

df['Time'] = pd.to_datetime(df['Time'])

FirstTime = df['Time'].iloc[0]

def hour_rounder(t):
    return (t.replace(second=0, microsecond=0, minute=0, hour=t.hour)
               -timedelta(hours=t.minute//15))

StartTime = hour_rounder(FirstTime)
StartTime = datetime.time(StartTime)

print(StartTime)

出局:

07:00:00

我不明白自己在做什么错?

2 个答案:

答案 0 :(得分:3)

- timedelta(hours=t.minute//15)

如果分钟是20,则minute // 15等于1,因此您要减去一小时。

尝试以下方法:

return t.replace(second=0, microsecond=0, minute=(t.minute // 15 * 15), hour=t.hour)

答案 1 :(得分:2)

使用.dt.floor('15min')向下舍入到15分钟。

import pandas as pd
df = pd.DataFrame({'Time': pd.date_range('2018-01-01', freq='13.141min', periods=13)})

df['prev_15'] = df.Time.dt.floor('15min')

输出:

                      Time             prev_15
0  2018-01-01 00:00:00.000 2018-01-01 00:00:00
1  2018-01-01 00:13:08.460 2018-01-01 00:00:00
2  2018-01-01 00:26:16.920 2018-01-01 00:15:00
3  2018-01-01 00:39:25.380 2018-01-01 00:30:00
4  2018-01-01 00:52:33.840 2018-01-01 00:45:00
5  2018-01-01 01:05:42.300 2018-01-01 01:00:00
6  2018-01-01 01:18:50.760 2018-01-01 01:15:00
7  2018-01-01 01:31:59.220 2018-01-01 01:30:00
8  2018-01-01 01:45:07.680 2018-01-01 01:45:00
9  2018-01-01 01:58:16.140 2018-01-01 01:45:00
10 2018-01-01 02:11:24.600 2018-01-01 02:00:00
11 2018-01-01 02:24:33.060 2018-01-01 02:15:00
12 2018-01-01 02:37:41.520 2018-01-01 02:30:00

如果需要分别获取最近的15分钟或接下来的15分钟间隔,则还有.dt.round().dt.ceil()