四舍五入并舍入时间

时间:2020-02-26 20:22:48

标签: python mysql python-3.x datetime jupyter-notebook

我是python的新手,我需要在python中找出一种解决方案,该解决方案可以将时间> 30分钟舍入为“下一分钟00秒”,将时间<30分钟舍入为“之前的分钟00秒”。我尝试了几种方法,例如将以分钟为单位的时间转换为timedelta类型,并从另一个包含相同分钟数的变量中减去该时间,但是它没有用。 我还应用了其他一些相关问题中提到的一些技术,但是没有用。时间已经通过pd.to_datetime命令转换为datetime格式。

以下是示例数据:

df name: Order_data  
column_name: Only_time

11:10:40  
09:13:26  
21:29:50  
19:13:37  
21:09:15  
19:51:43  
08:55:57  
13:31:01  
18:21:16

2 个答案:

答案 0 :(得分:0)

我假设您要转换为> 30 seconds,而不是minutes


编辑:使用dt.round()60S的{​​{1}}

T

文档:pandas.DatetimeIndex.roundtimeseries offset aliases


OLD :这是原始方法。

我将字符串转换为整数值,进行计算,然后将值转换回字符串

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

 df['rounded'] = df['Only_time'].dt.round('60S')
 df['rounded'] = df['Only_time'].dt.round('T')

结果

import pandas as pd

df = pd.DataFrame()

df['Only_time'] = '''11:10:40
09:13:26
21:29:50
19:13:37
21:09:15
19:51:43
08:55:57
13:31:01
18:21:16'''.split('\n')

def round_time(text):
    hours   = int(text[:2])
    minutes = int(text[3:-3])
    seconds = int(text[-2:])

    if seconds < 30:
        seconds = 00                  
    else:
        seconds = 00
        minutes += 1
        if minutes == 60:
            hours += 1
            minutes = 00

    return '{:02}:{:02}:{:02}'.format(hours, minutes, seconds)

df['rounded'] = df['Only_time'].apply(round_time)

print(df)

答案 1 :(得分:0)

def round_minutes(x):
  offset = 1 if x.second>30 else 0
  return x.replace(minute=x.minute+offset, second=0)

df['Only_time'] = df['Only_time'].apply(round_minutes)