使用python實現一個簡單的時間戳和日期的相互轉換
現在查詢某個時間對應的時間戳方法很簡單,直接百度一下:時間戳在線轉換 即可搜到好多時間戳在線轉換工具。但如果公司限制訪問外網時,時間戳在線轉換就無法使用,這時,可以利用python的內置模塊time,來實現一個簡單的時間戳和日期轉換。
具體代碼如下:
#encoding:utf-8 import time class TimeConvert(object): """ 時間格式轉換 """ def timestamp_to_date(self,timestamp,format_date="%Y-%m-%d %H:%M:%S"): """ 時間戳轉換為日期 @timestamp 需要轉換的時間戳 @format_date 指定日期格式 %Y:年,%m:月,%d:日,%H:小時,%M:分組,%S:秒,默認格式:%Y-%m-%d %H:%M:%S """ try: # 判斷時間戳類型為:秒 還是毫秒 if len(str(timestamp)) == 10: lt = time.localtime(timestamp) else: lt = time.localtime(timestamp/1000) date_value = time.strftime(format_date,lt) return {"時間戳":timestamp,"對應日期":date_value} except Exception as e: raise(e) def date_to_timestamp(self,date_value): """ 日期轉成時間戳 @date_value 需要轉換的日期,格式必須為:年-月-日 時:分:秒 """ try: t_tuple = time.strptime(date_value,"%Y-%m-%d %H:%M:%S") print(t) except Exception as e: raise("時間格式應為:年-月-日 時:分:秒") finally: return {"時間":date_value,"時間戳":int(time.mktime(t_tuple))} if __name__=="__main__": test = TimeConvert() print(test.timestamp_to_date(1720329139790,format_date="%Y-%m-%d")) print(test.date_to_timestamp("2024-07-07 12:16:13"))
運行結果:


浙公網安備 33010602011771號