python 日期时间学习
import datetime import time from datetime import timedelta class TimeUtil: """ staticmethod:静态方法,参数没有要求,和类没有绑定关系,跟全局变量差不多 classmethod:类方法,是一个函数修饰符,第一个参数是cls """ @staticmethod def get_current_year() -> int: """ :return: 返回当前年份 """ return datetime.datetime.now().year @staticmethod def get_current_month() -> int: """ :return: 返回当年月份 """ return datetime.datetime.now().month @staticmethod def get_current_day() -> int: """ :return: 返回当年日期 """ return datetime.datetime.now().day @staticmethod def get_current_hour() -> int: """ :return: 返回当前的小时数 """ return datetime.datetime.now().hour @staticmethod def get_current_date(): """ :return: 获取当前的的年月日 """ return time.strftime('%Y%m%d', time.localtime(time.time())) @staticmethod def get_timestamp(): """ :return: 获取当前时间戳 """ return time.time() @staticmethod def get_current_time(): """ :return: 当前日期时间 """ now = time.strftime('%Y-%m-%d %H:%M', time.localtime(time.time())) return now @staticmethod def time_cal(mode, num, time_delta=None): """ :mode: 返回参数的格式,如 "%Y-%m-%d %H:%M" :time_delta: None(天) hour(小时) min(分钟) :return: 返回当前时间 + n天/小时/分钟 """ if time_delta is None: res = datetime.datetime.now() + timedelta(days=num) return res.strftime(mode) elif time_delta == 'hour': res = datetime.datetime.now() + timedelta(hours=num) return res.strftime(mode) elif time_delta == 'min': res = datetime.datetime.now() + timedelta(minutes=num) return res.strftime(mode) else: raise "time_delta参数异常!" if __name__ == '__main__': print(TimeUtil.time_cal(mode="%Y-%m-%d %H:%M", num=1, time_delta='min'))