簡體   English   中英

舍入並舍入時間

[英]Round off and round down the time

我是 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 seconds ,而不是minutes


編輯:使用dt.round() woth 60ST

 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時間序列偏移別名


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
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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM