Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中将数据帧中的日期时间舍入为10分钟的日期时间_Python_Datetime_Rounding - Fatal编程技术网

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

如何在Python中将数据帧中的日期时间舍入为10分钟的日期时间,python,datetime,rounding,Python,Datetime,Rounding,我有一列数据时间,格式为:2015-06-25 03:29:58,我相信是datetime64。 我想把它们四舍五入到最接近的十分钟 i、 e 我已经到处寻找这个问题的答案,有几个线程和舍入时间的解决方案,例如: 然而,这种方法只能向下取整,不能向上取整 我也见过其他解决方案,但无法解决如何将它们应用于数据帧中的日期时间 我已经尝试了许多不同版本的: from pandas import * import datetime rounded_ten = lambda dt: datetime

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

i、 e

我已经到处寻找这个问题的答案,有几个线程和舍入时间的解决方案,例如:

然而,这种方法只能向下取整,不能向上取整

我也见过其他解决方案,但无法解决如何将它们应用于数据帧中的日期时间

我已经尝试了许多不同版本的:

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

任何帮助都将不胜感激。

试试以下方法:

四舍五入=λt:t.替换(分钟=t.分钟/10*10)。替换(秒=0)+局部时差('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)

然而,这种方法只能向下取整,不能向上取整

您可以将其与以下公式组合:

从日期时间导入时间增量
增量=时间增量(分钟=10)
df['']=df['')。应用(lambda dt:ceil_dt(dt,delta))

我在pd:NameError上遇到错误:未定义名称“pd”。我应该导入其他东西,还是定义其他东西?我像这样导入熊猫:
将熊猫导入为pd
我想你可以删除
pd
,我非常感谢你花时间写这篇文章,但我目前无法让它工作。我得到一个错误:“需要整数参数,得到浮点”。我试图编辑代码来创建整数,但它不起作用。另外,请您再告诉我一点代码对我的学习有什么作用好吗?如果您遇到这个错误,可能意味着您使用的是Python 3.xx,或者您导入了除法函数,即从未来导入除法。我正在使用Python 2.xx。在Python3及以上版本中,除法运算符的行为不同。请参见:。我更新了我的答案,它现在不应该给出那个错误。
rounded_ten = lambda t: (t+pd.Timedelta('5 minutes')).replace(minute=(t+pd.Timedelta('5 minutes')).minute//10*10).replace(second=0)
from datetime import timedelta

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