Python datetime模块:表示昨天,上个小时,上个月

时间不是能随便加减,要用到datetime内部的datetime.timedelta()
用下面代码方便准确的获取昨天,上个小时,上个月。

import datetime

today = datetime.datetime.now().day
yesterday = (datetime.datetime.now() - datetime.timedelta(days=1)).day

hour = datetime.datetime.now().hour
last_hour = (datetime.datetime.now() - datetime.timedelta(minutes=60)).hour

month = datetime.datetime.now().replace(day=1).month
last_month = (datetime.datetime.now().replace(day=1) - datetime.timedelta(days=1)).month

你可能感兴趣的:(Python datetime模块:表示昨天,上个小时,上个月)