開發中經常會對時間格式處理,對於時間數據,比如2019-02-28 10:23:29,有時需要日期與時間戳進行相互轉換,在Python3中主要用到time模塊,相關的函數如下:
其中unix_time函數是正常時間轉unix時間戳,date_time是unix時間轉正常時間如年月日時分秒:
import time """ 日期轉時間戳 """ def unix_time(dt): # 轉換成時間數組 timeArray = time.strptime(dt, "%Y-%m-%d %H:%M:%S") # 轉換成時間戳 timestamp = int(time.mktime(timeArray)) return timestamp """ 時間戳轉日期 """ def custom_time(timestamp): # 轉換成localtime time_local = time.localtime(timestamp) # 轉換成新的時間格式(2016-05-05 20:28:54) dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local) return dt time_now = '2019-02-28 10:23:29' unix_t = unix_time(time_now) custom_t = custom_time(unix_t) print(unix_t) # 1551320609 print(custom_t) # 2019-02-28 10:23:29 # 如果是自定義的時間格式轉換呢,思路方法雷同,比如下: """ 時間用指定格式顯示,比如 年-月-日 轉 年/月/日 """ dt = "2020-10-10 22:20:20" # 轉為數組 timeArray = time.strptime(dt, "%Y-%m-%d %H:%M:%S") # 轉為其它顯示格式 customTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray) print(customTime) # 2020/10/10 22:20:20 """ 時間用指定格式顯示,比如 年/月/日 轉 年-月-日 """ dt = "2020/10/10 22:20:20" timeArray = time.strptime(dt, "%Y/%m/%d %H:%M:%S") customTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) print(customTime) # 2020-10-10 22:20:20