python 万能时间格式转换

def clean_date(old_date, fmt_str=None) -> str:
"""
格式化时间
@param fmt_str: format date str
@param old_date: 各种时间类型
@return: 2019-03-08
"""

# 时间戳
if isinstance(old_date, int):
d = datetime.datetime.fromtimestamp(old_date)
return d.strftime('%Y-%m-%d')

# 自定义格式
if fmt_str:
# format ref: https://juejin.im/post/5be26d15f265da61776b720a
old_date = datetime.datetime.strptime(old_date, fmt_str)
if old_date.hour == old_date.minute == old_date.second == 0:
return old_date.strftime('%Y-%m-%d')

return old_date.strftime('%Y-%m-%d')

# 2019年3月8日, 19年3月8日, 2008-09-26, 2008-09-26T01:51:42.000Z
date_f = re.search('(?P<year>d+)[-/年](?P<month>d+)[-/月](?P<day>d+)[-/日]?.?'
'(?P<hour>d+)?[-:/时]?(?P<minute>d+)?[-:/分]?(?P<second>d+)?[-:/秒]?',
old_date)
if date_f:
year, month, day = date_f.group('year'), date_f.group('month').zfill(2), date_f.group('day').zfill(2)
hour, minute, second = date_f.group('hour'), date_f.group('minute'), date_f.group('second')
if len(year) == 2:
year = '20' + year

if hour:
if minute is None:
minute = str(randint(0, 59))
if second is None:
second = str(randint(0, 59))

hour, minute, second = hour.zfill(2), minute.zfill(2), second.zfill(2)
return year + '-' + month + '-' + day

else:
return year + '-' + month + '-' + day

原文地址:https://www.cnblogs.com/baili-luoyun/p/13631175.html