如何将日期时间向上舍入到上一个小时?例如:
print datetime.now().replace(microsecond=0)
>> 2017-01-11 13:26:12.0
向下舍入到前一小时:2017-01-11 12:00:00.0
答案 0 :(得分:27)
如果您希望向下舍入到小时,则只需将microsecond
,seconds
和minutes
全部替换为零:
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} }和seconds
与minutes
,然后从中减去一小时:
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')