如何在 Python 中的数据框中将日期时间舍入为十分钟日期时间

How to round a datetime to ten minute datetime in a dataframe in Python

我有一列格式为 2015-06-25 03:29:58 的数据时间,我认为它在 datetime64 中。 我想将它们四舍五入到最接近的十分钟。

2015-06-25 03:29:58  =   2015-06-25 03:30:00
2015-06-25 03:24:58  =   2015-06-25 03:20:00
2015-06-25 03:59:58  =   2015-06-25 04:00:00

我找遍了这个问题的答案,有一些关于舍入时间的线程和解决方案,比如这个:

但是这种方法只能向下取整,不能向上取整

我也看到了其他解决方案,但不知道如何将它们应用于数据框中的日期时间。

我试过很多不同的版本:

from pandas import * 
import datetime

rounded_ten = lambda dt: datetime.datetime(dt.year, dt.month, dt.day,(dt.hour), 10*(round(dt.minute/10)))

dataframe1['Device Time'] = dataframe1['Device Time'].apply(rounded_ten)

但这不起作用,因为当您将 55 向上舍入时,它会给出 60 的答案。这在这种格式中是不可接受的。 我想应用一些 if 语句,但是我不明白如何将它们应用到这种格式。

如有任何帮助,我们将不胜感激。

试试这个:

rounded_ten = lambda t: t.replace(minute=t.minute/10*10).replace(second=0)+pd.Timedelta ('10 分钟')

我想我一开始误解了这个问题。这应该有效:

import pandas as pd

def rounded_ten(t):
    ''' add 5 minutes to the date first and then apply mathematical floor to the minute part.
    It's easier to apply mathematical floor operation on date parts instead of rounding because for example you cannot round up 58 seconds to 60 seconds but you can always apply floor and stay within the range.
    '''
    t=t+pd.Timedelta('5 minutes') 
    return t.replace(minute=t.minute//10*10).replace(second=0)

或者如果你想使用一个衬垫:

rounded_ten = lambda t: (t+pd.Timedelta('5 minutes')).replace(minute=(t+pd.Timedelta('5 minutes')).minute//10*10).replace(second=0)


However this method can only round down, not round up.

您可以将它与 Rounding up to nearest 30 minutes in python:

中的公式结合起来
from datetime import timedelta

delta = timedelta(minutes=10)
df['<column>'] = df['<column>'].apply(lambda dt: ceil_dt(dt, delta))