将日期时间向下舍入到前一小时
Round down datetime to previous hour
如何将日期时间向下舍入到前一小时?例如:
print datetime.now().replace(microsecond=0)
>> 2017-01-11 13:26:12.0
四舍五入到前一小时:2017-01-11 12:00:00.0
如果您想四舍五入到小时,您只需将 microsecond
、second
和 minute
替换为零即可:
print(datetime.now().replace(microsecond=0, second=0, minute=0))
如果您想向下舍入到 前 小时(如示例 2017-01-11 13:26:12.0
至 2017-01-11 12:00:00.0
中所述),请替换 microsecond
, second
和 minute
用零,然后减去一小时:
from datetime import datetime, timedelta
print(datetime.now().replace(microsecond=0, second=0, minute=0) - timedelta(hours=1))
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
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)
from datetime import datetime
import pandas as pd
currTime = datetime.now()
time = pd.to_datetime(currTime).floor('H')
如何将日期时间向下舍入到前一小时?例如:
print datetime.now().replace(microsecond=0)
>> 2017-01-11 13:26:12.0
四舍五入到前一小时:2017-01-11 12:00:00.0
如果您想四舍五入到小时,您只需将 microsecond
、second
和 minute
替换为零即可:
print(datetime.now().replace(microsecond=0, second=0, minute=0))
如果您想向下舍入到 前 小时(如示例 2017-01-11 13:26:12.0
至 2017-01-11 12:00:00.0
中所述),请替换 microsecond
, second
和 minute
用零,然后减去一小时:
from datetime import datetime, timedelta
print(datetime.now().replace(microsecond=0, second=0, minute=0) - timedelta(hours=1))
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
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)
from datetime import datetime
import pandas as pd
currTime = datetime.now()
time = pd.to_datetime(currTime).floor('H')