Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

1.1K
Vistas
Round time to nearest hour python

I was trying to round off time to the nearest hour in python in a dataframe.

Suppose if a timestamp is 2017-11-18 0:16 it should come as 2017-11-18 0:00 and 2017-11-18 1:56 should round off as 2017-11-18 2:00

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

I experimented a bit with jpp but ended up with a different solution as adding one hour at hour 23 crashed the thing.

from datetime import datetime, timedelta

now = datetime.now()

def hour_rounder(t):
    # Rounds to nearest hour by adding a timedelta hour if minute >= 30
    return (t.replace(second=0, microsecond=0, minute=0, hour=t.hour)
               +timedelta(hours=t.minute//30))

print(now)
print(hour_rounder(now))

Returns:

2018-02-22 23:42:43.352133
2018-02-23 00:00:00
over 4 years ago · Santiago Trujillo Denunciar

0

import pandas as pd

pd.Timestamp.now().round('60min').to_pydatetime()

Returns:

datetime.datetime(2018, 2, 23, 0, 0)
over 4 years ago · Santiago Trujillo Denunciar

0

This is one way.

from datetime import datetime

now = datetime.now()

def rounder(t):
    if t.minute >= 30:
        return t.replace(second=0, microsecond=0, minute=0, hour=t.hour+1)
    else:
        return t.replace(second=0, microsecond=0, minute=0)

now           # 2018-02-22 22:03:53.831589
rounder(now)  # 2018-02-22 22:00:00.000000
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda