时间格式化所使用的算法为:
""" 1.如果不在同一年 '%Y年%m月%d日' 2.如果在同一年 2.1 如果在同一个月 2.1.1 如果在同一天 '%H:%M' 2.1.2 如果是昨天 '昨天 %H:%M' 2.1.2 如果在同一周 '周x 00:00' 去除周日 的情况 2.2 否则 '%m月%d日 %H:%M' """
具体的python代码如下:
def fmtdt_str(dtstr, fmt): result = "" locale.setlocale(locale.LC_CTYPE, 'chinese') curtime = datetime.now() curYear = curtime.year curMonth = curtime.month str_time = datetime.strptime(dtstr, fmt) if str_time.year == curYear: if str_time.month == curMonth: days_interval = (curtime.day - str_time.day) if days_interval == 0: result = str_time.strftime("%H:%M") elif days_interval == 1: result = str_time.strftime("昨天 %H:%M") else: if curtime.strftime("%W") == str_time.strftime("%W"): week_str = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'] str_weekno = str_time.weekday() if str_weekno == 0: result = str_time.strftime("%m月%d日 %H:%M") else: result = str_time.strftime(week_str[str_weekno] + " %H:%M") else: result = str_time.strftime("%m月%d日 %H:%M") else: result = str_time.strftime("%m月%d日 %H:%M") else: result = str_time.strftime("%Y年%m月%d日") return result