我是Python新手,我需要在Python中找出一个解决方案,可以将时间> 30分钟四舍五入为“下一分钟00秒”,将时间< 30分钟四舍五入为“前一分钟00秒”。我尝试了几种方法,例如将以分钟为单位的时间转换为 timedelta 类型,并从另一个包含相同分钟的变量中减去它,但它不起作用。 我还应用了其他一些相关问题中提到的一些技术,但没有用。时间已经通过 pd.to_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()
为 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')
文档:pandas.DatetimeIndex.round和 timeseries offset aliases
<小时/>OLD:这是原始方法。
我将字符串转换为整数值,进行计算,然后将值转换回字符串
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)
结果
Only_time rounded
0 11:10:40 11:11:00
1 09:13:26 09:13:00
2 21:29:50 21:30:00
3 19:13:37 19:14:00
4 21:09:15 21:09:00
5 19:51:43 19:52:00
6 08:55:57 08:56:00
7 13:31:01 13:31:00
8 18:21:16 18:21:00
关于python - 对时间进行四舍五入和四舍五入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60421975/