【Python】日期格式转换 <字符串、datetime、date>
# coding:utf-8import datetimefrom dateutil.parser import parse from dateutil.relativedelta import relativedelta from loguru import logger as logs class date_transform: """日期格式转换""" def auto(self, d): """判断参数类型""" try: if type(d) == str: re = self.str_to_date(d) elif type(d) in [datetime.datetime, datetime.date]: re = self.date_to_str(d) else: re = d logs.error("参数格式不在转换内, 返回原参数内容") except Exception as e: re = d logs.error("转换失败, 返回原参数内容, 失败原因:{}".format(e)) finally: return re @staticmethod def str_to_date(d): """字符串转换为日期""" logs.info("字符串转换为日期:{}".format(parse(d))) return parse(d) @staticmethod def date_to_str_iso(d): """日期转换为字符串 ISO 8601是一种国际标准""" logs.info("日期转换为ISO标准字符串:{}".format(d.isoformat())) return d.isoformat() @staticmethod def date_to_str(d, f="%Y/%#m/%#d"): """日期转换为字符串""" logs.info("日期转换为字符串:{}".format(d.strftime(f))) return d.strftime(f) if __name__ == "__main__": """run""" a = date_transform().auto("2023-08-10") b = date_transform().auto(datetime.date.today()) c = date_transform().auto(datetime.datetime.now()) d = date_transform().date_to_str_iso(datetime.datetime.now()) logs.debug(date_transform().auto("000")) logs.debug(a) logs.debug(b) logs.debug(c) logs.debug(d)
执行结果
-------------------------------------------------------------------------------------
如果万事开头难 那请结局一定圆满 @ Phoenixy
-------------------------------------------------------------------------------------