35

How to round down datetime to previous hour? for example:

print datetime.now().replace(microsecond=0)
>> 2017-01-11 13:26:12.0

round down to previous hour: 2017-01-11 12:00:00.0

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
DougKruger
  • 4,424
  • 14
  • 41
  • 62
  • 5
    If your date is `2017-01-11 00:11:22`, do you want your date to be on the previous day? Do you need to consider Daylight Saving Time? – Vincent Savard Jan 11 '17 at 16:23
  • 1
    no, I want it to be `2017-01-11 00:00:00` – DougKruger Jan 11 '17 at 16:32
  • 3
    @DougKruger: I'm a bit confused: you say you want to round down to the *previous* hour, but in your comment, you seem to only round down. Is this only the case at the beginning of a day? Or do I overlook something? – Willem Van Onsem Jan 11 '17 at 16:33

3 Answers3

77

Given you want to round down to the hour, you can simply replace microsecond, second and minute with zeros:

print(datetime.now().replace(microsecond=0, second=0, minute=0))

If you want to round down to the previous hour (as stated in the example 2017-01-11 13:26:12.0 to 2017-01-11 12:00:00.0), replace microsecond, second and minute with zeros, then subtract one hour:

from datetime import datetime, timedelta

print(datetime.now().replace(microsecond=0, second=0, minute=0) - timedelta(hours=1))

Example in the shell:

$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime, timedelta
>>> print(datetime.now().replace(microsecond=0, second=0, minute=0) - timedelta(hours=1))
2017-01-11 16:00:00
Nathaniel Jones
  • 939
  • 1
  • 14
  • 25
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
12
from datetime import datetime, timedelta

n = datetime.now() - timedelta(hours=1)
new_date = datetime(year=n.year, month=n.month, day=n.day, hour=n.hour)
gipsy
  • 3,859
  • 1
  • 13
  • 21
4
from datetime import datetime
import pandas as pd

currTime = datetime.now()

floored = pd.to_datetime(currTime).floor('H').to_pydatetime()
Asclepius
  • 57,944
  • 17
  • 167
  • 143
Kobe Janssens
  • 310
  • 2
  • 13