python 實現(xiàn)仿微信聊天時間格式化顯示的代碼
更新時間:2020年04月17日 11:40:33 作者:xiaopengyaonixi
這篇文章主要介紹了python 實現(xiàn)仿微信聊天時間格式化顯示,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧
時間格式化所使用的算法為:
""" 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
總結(jié)
到此這篇關(guān)于python 實現(xiàn)仿微信聊天時間格式化顯示的代碼的文章就介紹到這了,更多相關(guān)python時間格式化顯示內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:
- Python獲取、格式化當前時間日期的方法
- 使用Python將字符串轉(zhuǎn)換為格式化的日期時間字符串
- Python之time模塊的時間戳,時間字符串格式化與轉(zhuǎn)換方法(13位時間戳)
- Python格式化日期時間操作示例
- python日期時間轉(zhuǎn)為字符串或者格式化輸出的實例
- python 時間戳與格式化時間的轉(zhuǎn)化實現(xiàn)代碼
- python中日期和時間格式化輸出的方法小結(jié)
- Python datetime時間格式化去掉前導0
- Python 時間操作例子和時間格式化參數(shù)小結(jié)
- python數(shù)據(jù)清洗中的時間格式化實現(xiàn)
相關(guān)文章
對pandas中時間窗函數(shù)rolling的使用詳解
今天小編就為大家分享一篇對pandas中時間窗函數(shù)rolling的使用詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11python enumerate函數(shù)的使用方法總結(jié)
這篇文章主要介紹了python enumerate使用方法總結(jié),enumerate函數(shù)用于遍歷序列中的元素以及它們的下標,有興趣的可以了解一下2017-11-11