python datetime round to nearest hour

Solutions on MaxInterview for python datetime round to nearest hour by the best coders in the world

showing results for - "python datetime round to nearest hour"
Christopher
07 Feb 2019
1from datetime import datetime, timedelta
2
3now = datetime.now()
4
5def hour_rounder(t):
6    # Rounds to nearest hour by adding a timedelta hour if minute >= 30
7    return (t.replace(second=0, microsecond=0, minute=0, hour=t.hour)
8               +timedelta(hours=t.minute//30))
9
10print(now)
11print(hour_rounder(now))