對於爬蟲爬取到的文章存儲到數據庫時,有時需要到文檔發佈的時間進行處理。此時要用到datetime將時間精確到某一個單位。 # conding=utf8 from datetime import datetime, timedelta import time a = datetime.now() print(a.strftime("%Y-%m-%d %H:%M:%S")) # 獲取當前時間精確到秒數 # 2018-01-28 23:33:18 print(a.strftime("%Y-%m-%d %H:%M")) # 獲取當前時間精確到分鐘 # 2018-01-28 23:33 print(a.strftime("%Y-%m-%d %H")) # 獲取當前時間精確到小時 # 2018-01-28 23 print(a.strftime("%Y-%m-%d")) # 獲取當前時間精確帶天 # 2018-01-28 print((a - timedelta(seconds=5)).strftime("%Y-%m-%d %H:%M:%S")) # 2018-01-28 23:36:39 print((a - timedelta(minutes=5)).strftime("%Y-%m-%d %H:%M")) # 2018-01-28 23:28 print((a - timedelta(hours=5)).strftime("%Y-%m-%d %H")) # 2018-01-28 18 print((a - timedelta(days=5)).strftime("%Y-%m-%d")) # 2018-01-23