python 對於時間的處理 datetime str字串 時間戳 相互轉換
阿新 • • 發佈:2020-10-13
對於時間的處理
獲取當前時間的datetime格式 datetime.datetime.now() 1. 將datetime格式轉換為指定格式的str輸出 datetime.strftime(start_time,"%Y-%m-%d %H:%M:%S") # 這裡的 start_time 是 資料庫裡的datetime格式 2. 將datetime格式轉換為時間戳 start_time.replace(tzinfo=datetime.timezone.utc).timestamp() # 或者 time.mktime(start_time.timetuple()) # 這裡的 start_time 是 資料庫裡的datetime格式 3. 返回前端時將資料庫記憶體的datetime格式轉換為指定格式的str輸出 models.TaskList.objects.filter(pk=task_id).first().active_time.strftime('%Y-%m-%d %H:%M:%S') 4. 獲取當前時間戳 time.time() 5. 將字串str轉換為time模組能處理的struct_time格式 str_time = '2022-02-03 00:00:00' time.strptime(str_time, '%Y-%m-%d %H:%M:%S') 6. 將字串str轉換成時間戳 time.mktime(time.strptime(str_time, "%Y-%m-%d %H:%M:%S")) 7. 將字串str轉換為datetime datetime.datetime.strptime(str_time, "%Y-%m-%d %H:%M:%S") 8. 將時間戳轉換為字串str time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) # time.time() 是時間戳