- Python round time to nearest 15 minutes
- How do you round to the nearest quarter hour from a DateTime object in Python?
- Python round time to nearest 15 minutes
- Python round DateTime up to nearest 15 minutes using ceil
- Python round DateTime down to nearest 15 minutes using floor
- Related articles
- References
- Stephen Allwright Twitter
- Pandas round DateTime to minute
- How does Pandas round to the nearest minute?
- Pandas round DateTime to minute
- Pandas round DateTime to minute and return as integer
- Round Pandas DateTime down to nearest minute
- Round Pandas DateTime up to nearest minute
- Related articles
- References
- Stephen Allwright Twitter
- Время округления в Python
- 7 ответов
- Ещё вопросы
Python round time to nearest 15 minutes
Being able to round a DateTime object in Python to the nearest quarter hour can be extremely helpful for feature engineering. In this post, I will explain how to do this simply in multiple variations.
Being able to round a DateTime object in Python to the nearest quarter hour can be extremely helpful for feature engineering. In this post, I will explain how to do this simply in multiple variations.
How do you round to the nearest quarter hour from a DateTime object in Python?
Python doesn’t have built-in functionality for rounding a DateTime to the nearest quarter hour, as it does for seconds, minutes, and hours. Therefore, in order to round to the nearest 15 minutes, we have to create a custom function to do this.
Python round time to nearest 15 minutes
In order to round to the nearest 15 minutes we need to use a combination of round and timedelta . In this code example we combine these operations into a simple function whose inputs are the DateTime that will be rounded, and the time window to round towards, which in our case will be 15 minutes.
from datetime import datetime, timedelta def round_dt(dt, delta): return datetime.min + round((dt - datetime.min) / delta) * delta delta = timedelta(minutes=15) dt = datetime(2022, 9, 1, 14, 28, 0) print(round_dt(dt,delta)) dt = datetime(2022, 9, 1, 14, 20, 0) print(round_dt(dt,delta)) """ Output: 2022-09-01 14:30:00 2022-09-01 14:15:00 """
Python round DateTime up to nearest 15 minutes using ceil
The previous example uses round which will round to the nearest 15 minutes, whether that is up or down. However, we may always want to round upwards. This requires only a tiny change to the example we saw above, where we use math.ceil instead of round .
from datetime import datetime, timedelta import math def round_dt(dt, delta): return datetime.min + math.ceil((dt - datetime.min) / delta) * delta delta = timedelta(minutes=15) dt = datetime(2022, 9, 1, 14, 28, 0) print(round_dt(dt,delta)) dt = datetime(2022, 9, 1, 14, 20, 0) print(round_dt(dt,delta)) """ Output: 2022-09-01 14:30:00 2022-09-01 14:30:00 """
Python round DateTime down to nearest 15 minutes using floor
If you want to always round down to the nearest 15 minutes then we need to use math.floor instead of round .
from datetime import datetime, timedelta import math def round_dt(dt, delta): return datetime.min + math.floor((dt - datetime.min) / delta) * delta delta = timedelta(minutes=15) dt = datetime(2022, 9, 1, 14, 28, 0) print(round_dt(dt,delta)) dt = datetime(2022, 9, 1, 14, 20, 0) print(round_dt(dt,delta)) """ Output: 2022-09-01 14:15:00 2022-09-01 14:15:00 """
Related articles
References
Stephen Allwright Twitter
I’m a Data Scientist currently working for Oda, an online grocery retailer, in Oslo, Norway. These posts are my way of sharing some of the tips and tricks I’ve picked up along the way.
Pandas round DateTime to minute
Being able to round a DateTime object in Pandas to the nearest minute can be extremely helpful for feature engineering. In this post, I will walk through how to do this simply in multiple variations.
Being able to round a DateTime object in Python to the nearest minute can be extremely helpful for feature engineering. In this post, I will walk through how to do this simply in multiple variations.
How does Pandas round to the nearest minute?
In order to round a DateTime object to the nearest minute, you need to use the round operation from Pandas on the DateTime column and specify the frequency that you want to use. For rounding to the nearest minute you will need to use round(«min») .
Pandas round DateTime to minute
Below is a simple example of how you can round to the nearest minute and return this as a DateTime object.
import pandas as pd df = pd.DataFrame( columns=["datetime"], data=pd.date_range("1/1/2022 20:30:28", periods=6, freq="s")) df["minute_datetime"] = df["datetime"].dt.round("min") """ Output: datetime minute_datetime 0 2022-01-01 20:30:28 2022-01-01 20:30:00 1 2022-01-01 20:30:29 2022-01-01 20:30:00 2 2022-01-01 20:30:30 2022-01-01 20:30:00 3 2022-01-01 20:30:31 2022-01-01 20:31:00 4 2022-01-01 20:30:32 2022-01-01 20:31:00 5 2022-01-01 20:30:33 2022-01-01 20:31:00 """
Pandas round DateTime to minute and return as integer
You may also want to return the minute not as a DateTime object but as an integer instead, this is possible with just a small addition to the previous example.
import pandas as pd df = pd.DataFrame( columns=["datetime"], data=pd.date_range("1/1/2022 20:30:28", periods=6, freq="s")) df["minute_integer"] = df["datetime"].dt.round("min").dt.minute """ Output: datetime minute_integer 0 2022-01-01 20:30:28 30 1 2022-01-01 20:30:29 30 2 2022-01-01 20:30:30 30 3 2022-01-01 20:30:31 31 4 2022-01-01 20:30:32 31 5 2022-01-01 20:30:33 31 """
Round Pandas DateTime down to nearest minute
The round operation from Pandas rounds to the nearest minute, but what if you want to always round down to the nearest minute? Well, for this you need to use the floor operation.
import pandas as pd df = pd.DataFrame( columns=["datetime"], data=pd.date_range("1/1/2022 20:30:28", periods=6, freq="s")) df["round_down_minute_datetime"] = df["datetime"].dt.floor("min") df["round_down_minute_integer"] = df["datetime"].dt.floor("min").dt.minute """ Output: datetime round_down_minute_datetime round_down_minute_integer 0 2022-01-01 20:30:28 2022-01-01 20:30:00 30 1 2022-01-01 20:30:29 2022-01-01 20:30:00 30 2 2022-01-01 20:30:30 2022-01-01 20:30:00 30 3 2022-01-01 20:30:31 2022-01-01 20:30:00 30 4 2022-01-01 20:30:32 2022-01-01 20:30:00 30 5 2022-01-01 20:30:33 2022-01-01 20:30:00 30 """
Round Pandas DateTime up to nearest minute
Likewise, if you want to always round up the nearest minute you need to use the ceil operation.
import pandas as pd df = pd.DataFrame( columns=["datetime"], data=pd.date_range("1/1/2022 20:26:00", periods=10, freq="min")) df["round_up_minute_datetime"] = df["datetime"].dt.ceil("min") df["round_up_minute_integer"] = df["datetime"].dt.ceil("min").dt.minute """ Output: datetime round_up_minute_datetime round_up_minute_integer 0 2022-01-01 20:30:28 2022-01-01 20:31:00 31 1 2022-01-01 20:30:29 2022-01-01 20:31:00 31 2 2022-01-01 20:30:30 2022-01-01 20:31:00 31 3 2022-01-01 20:30:31 2022-01-01 20:31:00 31 4 2022-01-01 20:30:32 2022-01-01 20:31:00 31 5 2022-01-01 20:30:33 2022-01-01 20:31:00 31 """
Related articles
References
Stephen Allwright Twitter
I’m a Data Scientist currently working for Oda, an online grocery retailer, in Oslo, Norway. These posts are my way of sharing some of the tips and tricks I’ve picked up along the way.
Время округления в Python
Соответствующие типы времени, о которых я могу думать:
Хотите ли вы округлить дату до ближайшей «части» (т. Е. 20:11:10 с округлением до ближайшего часа, чтобы получить 20:00:00), или — как показывает ваш пример — получить остаток после округления до ближайшей части (т.е. 20 : 11: 10 до ближайшего часа дает 11:13)?
7 ответов
Как насчет использования 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
print roundTime(datetime.datetime(2012,12,31,23,44,59,1234),roundTo=60*60) 2013-01-01 00:00:00
Вы можете конвертировать оба раза в секунды, выполнять modulo operati
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)))
Это будет округлять данные времени до разрешения, заданного в вопросе:
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
Я использую следующий фрагмент кода для округления до следующего часа:
import datetime as dt tNow = dt.datetime.now() # round to the next full hour tNow -= dt.timedelta(minutes = tNow.minute, seconds = tNow.second, microseconds = tNow.microsecond) tNow += dt.timedelta(hours = 1)
На самом деле это единственный ответ, который напрямую отвечает на заголовок вопроса, который касается округления (и это именно то, что я ищу). Тело вопроса противоречит названию. Это просто плохой вопрос. Спасибо, ПТГ.
Осторожно: если tNow уже округлено до ближайшего часа, то оно будет увеличиваться на час вместо того, чтобы ничего не делать.
Я думаю, что я конвертирую время в секундах и использую стандартную модульную операцию с этой точки.
20:11:13 = 20*3600 + 11*60 + 13 = 72673 секунды
Это самое легкое решение, о котором я могу думать.
Если вы хотите возиться с особыми случаями, по модулю n секунд, где n находится в (2,3,4,5,10,12,15,20,30), можно выполнить только часть секунд.
def round_dt_to_seconds(dt): datetime.timedelta(seconds=dt.seconds)
dt.seconds вызывает dt.seconds AttributeError . Кроме того, я не вижу, как эта функция делает что-нибудь. (он даже не возвращает значение)
Ещё вопросы
- 0 добавление HTML выбора стран в несколько мест
- 1 Приложение Android закрывается при добавлении класса-оболочки в манифест
- 0 .HTACCESS — Дамп сайт от производства до разработки
- 0 Qt: Сигналы и слоты против C ++: передача сообщений
- 0 Выберите количество с двумя условиями в одном псевдониме
- 0 Не удается правильно загрузить растровое изображение из памяти
- 1 Gradle, Вы не приняли лицензионные соглашения (Android SDK)
- 1 Новичок Рок, Бумага, Ножницы Игровой Синтаксис Python
- 0 HTML-функция вызова JavaScript при загрузке
- 0 Ответ на запрос mysqli остается пустым, несмотря на соединение с базой данных
- 0 Угловой JS передает массив строк в директиву
- 0 Плагин jQuery, сохраняйте ссылку на оригинальный элемент
- 0 Отменить в ожидании recv?
- 1 Когда переопределять, а когда подписываться на делегат?
- 1 Реструктуризация разбора результатов анализа многопоточного файла журнала
- 0 получить доступ к главной таблице из реплики
- 1 Это хорошая практика, чтобы установить все поля на ноль?
- 0 Контроллер ресурсов показывает белый экран в Laravel 4, несмотря на рабочие маршруты
- 0 перенести значения из функции в другой файл php
- 0 путевые точки бесконечной прокрутки не работали
- 0 Получить данные из базы данных и создать необходимый формат JSON
- 0 нижний div не по центру
- 1 Импорт телефонных номеров с облачным питоном Google Python
- 1 NodeJs — Как визуализировать EJS в рендеринге EJS?
- 0 ион-бесконечный свиток терпит неудачу с ионным
- 0 OpenCV2 с Eclipse
- 0 Как нажать на элемент, используя другой связанный элемент?
- 0 Добавление двух карт Google на одну страницу HTML
- 0 Вставить несколько строк в laravel с полезной нагрузкой JSON
- 1 Некоторые пользовательские маркеры не отображаются на Android-native-картах реакции
- 1 Spring JPA Hibernate обрабатывает большие базы данных
- 0 AngularJS Directive Countup.JS получить данные из модели
- 1 Реагировать на родной плоский список, а не на ожидаемое поведение
- 0 Почему javascript (jquery), если операторы не работают, как операторы php if? И что такое решение?
- 1 Repl.it javascript classroom — бесконечный цикл
- 0 Исходя из идеи, MySQLNonTransientConnectionException: не удалось создать соединение с сервером базы данных
- 0 Поверните строки таблицы в столбцы без результата
- 0 Получить элементы списка в массив
- 0 дополнительные элементы данных в объединенной структуре
- 1 развернуть / свернуть Анимация Android наполовину
- 1 Как получить имя кластера Cassandra, используя драйвер Python?
- 1 Android Retrofit2 / RxJava2 / Room — Простая обработка данных
- 1 Понимание «побочных эффектов» в Javascript с учетом функций первого класса
- 1 Как сделать анимированный круг?
- 1 Как получить маршрут REST API, такой как / api / library / 1 / books / 2 / dosomething? Q = params с WebAPI?
- 0 MFC C ++: как настроить список?
- 1 Нужно ли предоставлять методы получения / установки для полей Auditable в Spring Data?
- 1 Категориальные переменные в несколько столбцов
- 0 Angular UI Router загружен, но не передает параметры
- 1 ThreadPool и методы с циклами while (true)?