我想将HH:MM:SS四舍五入到下一个季度。 举一些例子:
我有以下数据:
12:25:00 PM
03:33:00 PM
03:36:00 PM
03:48:00 PM
我想得到以下结果:
12:30:00 PM
03:45:00 PM
03:45:00 PM
04:00:00 PM
答案 0 :(得分:0)
只需添加timedelta
的下一个15的倍数与当前分钟之间的差值
>>> from datetime import datetime,timedelta
>>> time_lst = ['12:25:00 PM', '03:33:00 PM', '03:36:00 PM', '03:48:00 PM']
>>>
>>> dt_list = [datetime.strptime(time, "%H:%M:%S %p") for time in time_lst]
>>> [(dt + timedelta(minutes=15*(int(dt.minute/15)+1) - dt.minute)).strftime("%H:%M:%S %p") for dt in dt_list]
['12:30:00 PM', '03:45:00 AM', '03:45:00 AM', '04:00:00 AM']
>>>
答案 1 :(得分:0)
import time
from math import floor, ceil
SECONDS_PER_15MIN = 15 * 60;
time_now = time.time() # somehow get your time in seconds
print("now", time.asctime(time.localtime(time_now)))
# Count how often 15minutes fits in there
count = time_now/SECONDS_PER_15MIN
# Round it down or up and multiply with the number of seconds in 15 minutes again to get the total number of seconds
time_rounded_down = floor(count) * SECONDS_PER_15MIN
time_rounded_up = ceil(count) * SECONDS_PER_15MIN
print("down", time.asctime(time.localtime(time_rounded_down)))
print("up", time.asctime(time.localtime(time_rounded_up)))
答案 2 :(得分:0)
类似这样的东西
import math
lst = ['12:25:00 PM',
'03:33:00 PM',
'03:36:00 PM',
'03:48:00 PM']
new_time_lst = []
for entry in lst:
elements = entry.split(':')
hours = int(elements[0])
minutes = int(elements[1])
q = math.floor(minutes / 15)
if q < 3:
q += 1
else:
q = 0
hours += 1
hours_str = '0' + str(hours) if hours < 10 else str(hours)
q_str = str(q * 15)
elements[0] = hours_str
elements[1] = q_str
new_time = ':'.join(elements)
new_time_lst.append(new_time)
print(new_time_lst)
输出
['12:30:00 PM', '03:45:00 PM', '03:45:00 PM', '04:0:00 PM']
答案 3 :(得分:0)
感谢您的帮助。
我找到了一个更简单的方法,可以在这里分享:
在[1]:df ['Times']
0 2019-08-07 12:25:00
1 2019-08-07 15:33:00
2 2019-08-07 15:36:00
3 2019-08-07 15:48:00
df ['Times']。apply(lambda x:pd.Timestamp(x).ceil('15T'))
0 2019-08-07 12:30:00
1 2019-08-07 15:45:00
2 2019-08-07 15:45:00
3 2019-08-07 16:00:00