pandas.DatetimeIndex.round#
Perform round operation on the data to the specified freq .
Parameters freq str or Offset
The frequency level to round the index to. Must be a fixed frequency like ‘S’ (second) not ‘ME’ (month end). See frequency aliases for a list of possible freq values.
ambiguous ‘infer’, bool-ndarray, ‘NaT’, default ‘raise’
Only relevant for DatetimeIndex:
- ‘infer’ will attempt to infer fall dst-transition hours based on order
- bool-ndarray where True signifies a DST time, False designates a non-DST time (note that this flag is only applicable for ambiguous times)
- ‘NaT’ will return NaT where there are ambiguous times
- ‘raise’ will raise an AmbiguousTimeError if there are ambiguous times.
A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST.
- ‘shift_forward’ will shift the nonexistent time forward to the closest existing time
- ‘shift_backward’ will shift the nonexistent time backward to the closest existing time
- ‘NaT’ will return NaT where there are nonexistent times
- timedelta objects will shift nonexistent times by the timedelta
- ‘raise’ will raise an NonExistentTimeError if there are nonexistent times.
Index of the same type for a DatetimeIndex or TimedeltaIndex, or a Series with the same index for a Series.
Raises ValueError if the freq cannot be converted.
If the timestamps have a timezone, rounding will take place relative to the local (“wall”) time and re-localized to the same timezone. When rounding near daylight savings time, use nonexistent and ambiguous to control the re-localization behavior.
DatetimeIndex
>>> rng = pd.date_range('1/1/2018 11:59:00', periods=3, freq='min') >>> rng DatetimeIndex(['2018-01-01 11:59:00', '2018-01-01 12:00:00', '2018-01-01 12:01:00'], dtype='datetime64[ns]', freq='T') >>> rng.round('H') DatetimeIndex(['2018-01-01 12:00:00', '2018-01-01 12:00:00', '2018-01-01 12:00:00'], dtype='datetime64[ns]', freq=None)
>>> pd.Series(rng).dt.round("H") 0 2018-01-01 12:00:00 1 2018-01-01 12:00:00 2 2018-01-01 12:00:00 dtype: datetime64[ns]
When rounding near a daylight savings time transition, use ambiguous or nonexistent to control how the timestamp should be re-localized.
>>> rng_tz = pd.DatetimeIndex(["2021-10-31 03:30:00"], tz="Europe/Amsterdam")
>>> rng_tz.floor("2H", ambiguous=False) DatetimeIndex(['2021-10-31 02:00:00+01:00'], dtype='datetime64[ns, Europe/Amsterdam]', freq=None)
>>> rng_tz.floor("2H", ambiguous=True) DatetimeIndex(['2021-10-31 02:00:00+02:00'], dtype='datetime64[ns, Europe/Amsterdam]', freq=None)
Как округлить время в python?
Ребята, подскажите, есть ли какой либо простой способ или библиотека чтобы округлить время в Python?
Простой 1 комментарий
Спасибо ответившим, хоть это и не решило проблему. Я забыл уточнить, что округлять мне нужно по своим условиям, а именно только в том случае, если до полного часа осталось меньше минуты, и в меньшую сторону, если после часа прошло не более минуты. В этом случае предложенные варианты не работают, я написал свое решение, но выглядит оно ужасно ))
hh, ss = divmod(parsed_time, 3600)
if ss < 60:
mm = 0
elif 60 mm = ss // 60
elif ss > 3540:
mm = 0
hh += 1
return ‘:’.format(int(hh), int(mm))
Делите ваше количество секунд на количество секунд в часе (3600) — получаете количество часов. Округляете его до целого (метод round), затем умножаете на 3600. В результате у вас получится количество секунд в целом числе часов.
>>> def round_time(x): . hour_in_seconds = 60 * 60 . half_hour_in_seconds = 60 * 30 . if x % hour_in_seconds > half_hour_in_seconds: . return ((x // hour_in_seconds) + 1) * hour_in_seconds . else: . return (x // hour_in_seconds) * hour_in_seconds . >>> >>> str(datetime.timedelta(seconds=3590)) '0:59:50' >>> str(datetime.timedelta(seconds=round_time(3590))) '1:00:00' >>> str(datetime.timedelta(seconds=390)) '0:06:30' >>> str(datetime.timedelta(seconds=round_time(390))) '0:00:00' >>> str(datetime.timedelta(seconds=5390)) '1:29:50' >>> str(datetime.timedelta(seconds=round_time(5390))) '1:00:00' >>> str(datetime.timedelta(seconds=7390)) '2:03:10' >>> str(datetime.timedelta(seconds=round_time(7390))) '2:00:00'
Время округления в Python
Соответствующие типы, связанные со временем, о которых я могу думать:
Вы хотите округлить дату до ближайшей «части» (например, 20:11:10 с округлением до ближайшего часа дает 20:00:00) или — как предлагает ваш пример — получить остаток после округления до ближайшей части (т.е. 20:11:10 до ближайшего часа дает 11:13)? — Rob Cowie
Прости; Вместо «дата» читать «время» — Rob Cowie
7 ответы
print roundTime(datetime.datetime(2012,12,31,23,44,59,1234),roundTo=60*60) 2013-01-01 00:00:00
Как насчет использования datetime.timedelta s:
import time import datetime as dt hms=dt.timedelta(hours=20,minutes=11,seconds=13) resolution=dt.timedelta(seconds=10) print(dt.timedelta(seconds=hms.seconds%resolution.seconds)) # 0:00:03 resolution=dt.timedelta(minutes=10) print(dt.timedelta(seconds=hms.seconds%resolution.seconds)) # 0:01:13
Это будет работать с datetime.time но не с datetime.datetime как вы не учли дату — Джонатан
Это округлит данные о времени до разрешения, заданного в вопросе:
import datetime as dt current = dt.datetime.now() current_td = dt.timedelta(hours=current.hour, minutes=current.minute, seconds=current.second, microseconds=current.microsecond) # to seconds resolution to_sec = dt.timedelta(seconds=round(current_td.total_seconds())) print(dt.datetime.combine(current, dt.time(0)) + to_sec) # to minute resolution to_min = dt.timedelta(minutes=round(current_td.total_seconds() / 60)) print(dt.datetime.combine(current, dt.time(0)) + to_min) # to hour resolution to_hour = dt.timedelta(hours=round(current_td.total_seconds() / 3600)) print(dt.datetime.combine(current, dt.time(0)) + to_hour)
Думаю, я бы преобразовал время в секунды и с этого момента использовал бы стандартную операцию по модулю.
20:11:13 = 20*3600 + 11*60 + 13 = 72673 секунд
Это самое простое решение, о котором я могу думать.
Если вы хотите заморачиваться с особыми случаями, по модулю n секунд, где n находится в (2,3,4,5,10,12,15,20,30), можно использовать только часть секунд. — Пол МакДжи
Вы можете преобразовать оба времени в секунды, выполните операцию по модулю
from datetime import time def time2seconds(t): return t.hour*60*60+t.minute*60+t.second def seconds2time(t): n, seconds = divmod(t, 60) hours, minutes = divmod(n, 60) return time(hours, minutes, seconds) def timemod(a, k): a = time2seconds(a) k = time2seconds(k) res = a % k return seconds2time(res) print(timemod(time(20, 11, 13), time(0,0,10))) print(timemod(time(20, 11, 13), time(0,10,0)))