2011-08-03 46 views
2

我不想冒這個黑客的風險,因爲它涉及到datetime對象。基本上,我想要做的轉換如下:如何將(總是)時間四捨五入到最近的十位?

2010-04-21 06:37:53 -> 2010-04-21 06:40:00 
2010-08-26 02:54:00 -> 2010-08-26 03:00:00 
2010-04-21 06:37:12 -> 2010-04-21 06:40:00 
2010-08-26 11:54:19 -> 2010-08-27 00:00:00 

有沒有一個內置的方式做到這一點?

+0

'2010-08-26 11:50:00.001'呢?那應該是'11:50'還是'12:00'出來? – robert

+0

哦..我丟棄了微秒。所以這個應該達到'11:50' – Legend

回答

2

您需要將您的時間轉換爲unix時間戳並按照希望舍入時間戳。

round(Timestamp/60 seconds [minutes conversion]/10 [round precision]) * 60 * 10 [to get the timestamp back]

1

這似乎是爲我工作。

def round_up(tm): 
    upmins = math.ceil(float(tm.minute)/10)*10 
    diffmins = upmins - tm.minute 
    newtime = tm + datetime.timedelta(minutes=diffmins) 
    newtime = newtime.replace(second=0) 
    return newtime 

轉換:

2010-04-21 06:37:53 -> 2010-04-21 06:40:00 
2010-08-26 02:54:00 -> 2010-08-26 03:00:00 
2010-04-21 06:37:12 -> 2010-04-21 06:40:00 
2010-08-26 02:54:19 -> 2010-08-26 03:00:00 
2010-04-21 06:35:32 -> 2010-04-21 06:40:00 
0

四捨五入上的時間戳的工作原理:

MINUTES = 10. 

d = datetime.now() 
t = time.mktime(d.timetuple()) 
t = math.ceil((t // 60)/MINUTES) * 600 
d = datetime.fromtimestamp(t) 
0
dt += datetime.timedelta(minutes=9, seconds=59, microseconds=999999) 
dt.replace(minutes=dt.minutes-(dt.minutes%10), seconds=0, microseconds=0) 

第一部分增加了9分鐘,59.999999秒使結果總是四捨五入。秒部分減去多餘的分鐘以返回到10分鐘的邊界並將秒設置爲零。

2

你只想整理幾分鐘。即使您忽略了秒和微秒,您也會得到正確的答案。

在這種情況下,這是一個班輪:

def round_minutes(t): # t is a datetime object 
    return t - datetime.timedelta(minutes = t.minute - round(t.minute, -1), seconds = t.second, microseconds = t.microsecond) 

你拿的時間timedelta原來的每分鐘之間,並四捨五入分鐘到最近的10並應用差異。此外,爲了零秒和微秒,您也可以在增量中添加它們。

相關問題