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))
Here is what the above code is Doing:
1. We import the datetime module.
2. We create a variable called now, and set it equal to datetime.now().
3. We define a function called hour_rounder that takes in a time.
4. We return the time rounded to the nearest hour.
5. We print the current time.
6. We print the current time rounded to the nearest hour.