Python 把时间四舍五入

Python 把时间四舍五入,python,mysql,python-3.x,datetime,jupyter-notebook,Python,Mysql,Python 3.x,Datetime,Jupyter Notebook,我是python新手,我需要找出一个python解决方案,可以将时间从>30分钟到“下一分钟00秒”,将时间从30秒,而不是分钟 编辑:使用dt.round()woth60S或T 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') 医生:和 旧的:它

我是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

我假设您希望转换时间为
>30秒
,而不是
分钟


编辑:使用
dt.round()
woth
60S
T

 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)

我假设您希望转换时间为
>30秒
,而不是
分钟


编辑:使用
dt.round()
woth
60S
T

 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)

你是说30分钟还是30秒?显示您对数据的预期结果。我的意思是>30分钟。你提到的代码对我有用。谢谢你是说30分钟还是30秒?显示您对数据的预期结果。我的意思是>30分钟。你提到的代码对我有用。谢谢