1. 程式人生 > 程式設計 >python 實現仿微信聊天時間格式化顯示的程式碼

python 實現仿微信聊天時間格式化顯示的程式碼

時間格式化所使用的演算法為:

 """
    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

總結

到此這篇關於python 實現仿微信聊天時間格式化顯示的程式碼的文章就介紹到這了,更多相關python時間格式化顯示內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!