【问题标题】:How to round a datetime to ten minute datetime in a dataframe in Python如何在 Python 的数据框中将日期时间舍入到十分钟的日期时间
【发布时间】:2016-03-07 08:57:17
【问题描述】:

我有一列数据时间,格式为: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

我已经到处寻找这个问题的答案,有几个线程和解决方案来解决舍入时间,比如这个: How do I round datetime column to nearest quarter hour

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

我还看到了其他解决方案,但无法弄清楚如何将它们应用于数据框中的日期时间。

我尝试了很多不同的版本:

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 语句,但是我不明白如何将它们应用到这种格式。

任何帮助将不胜感激。

【问题讨论】:

    标签: python datetime rounding


    【解决方案1】:

    试试这个:

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

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

    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)
    

    【讨论】:

    • 我在 pd 上遇到错误:NameError: name 'pd' is not defined。我应该导入其他东西,还是定义其他东西?
    • 我像这样导入熊猫:import pandas as pd 我想你可以删除pd
    • 非常感谢您花时间写这篇文章,但我目前无法让它工作。我收到一个错误:“需要整数参数,得到浮点数”。我试图编辑代码来创建整数,但它不起作用。另外,您能告诉我更多关于代码对我的学习有什么作用吗?
    • 如果您收到该错误,可能意味着您正在使用 Python 3.xx 或导入除法函数,即 from __future__ import division。我正在使用 Python 2.xx。在 Python 3 及更高版本中,除法运算符的行为不同。看到这个:python.org/dev/peps/pep-0238。我更新了我的答案,它现在不应该给出那个错误。
    【解决方案2】:

    How do I round datetime column to nearest quarter hour
    但是这种方法只能向下取整,不能向上取整。

    您可以将其与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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-28
      • 1970-01-01
      • 2013-10-17
      • 1970-01-01
      • 2011-01-12
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多