将日期时间向下舍入到上一个小时

时间:2017-01-11 16:19:41

标签: python datetime rounding

如何将日期时间向上舍入到上一个小时?例如:

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

向下舍入到前一小时:2017-01-11 12:00:00.0

3 个答案:

答案 0 :(得分:27)

如果您希望向下舍入到小时,则只需将microsecondsecondsminutes全部替换为零:

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

如果您要向下舍入上一个小时(如示例2017-01-11 13:26:12.0中所述至2017-01-11 12:00:00.0),请替换microseconds,{{1} }和secondsminutes,然后从中减去一小时:

0

shell中的示例:

from datetime import datetime, timedelta

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

答案 1 :(得分:2)

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)

答案 2 :(得分:0)

from datetime import datetime
import pandas as pd

currTime = datetime.now()

time = pd.to_datetime(currTime).floor('H')