大家好,這裡是程序員晚楓.知識星球:Python讀者圈
在Python中,There are a variety of formats for representing time3種:時間戳、結構化時間、格式化時間,2個模塊:time、datetime.
今天我們來一起看一下.
時間戳表示的是從1970年1月1日00:00:00開始按秒計算的偏移量.
import time
time.time() # 時間戳
# 輸出:1659682465.1875775
time this way,Generally used for database storage,非常節省存儲空間.
The so-called structured time,You can understand it as categorizing time,分為了:年月日時分秒,Which category do you want to use,Which category can be directly taken out.
If we want to take out a time slice,Using this method is very simple,例如:Get the minutes of the current time.
import time
time.localtime().tm_min # 結構化時間
# 輸出:30
這個方法,Used to show time to users.
import time
time.strftime('%Y-%m-%d %H-%M-%S %A')# 格式化時間
# 輸出:'2022-08-04 19-08-35 Friday'
import datetime
datetime.datetime.now()#格式化時間
# 輸出:datetime.datetime(2022, 8, 4, 19, 9, 0, 328515)
in the code that generated the time earlier,我們使用了2個模塊:time和datetime,It seems that the functions between them are also duplicated.
既然有了time模塊,為什麼還要有datetime?That's for simplificationtime的使用.
datatime模塊重新封裝了time模塊,提供更多接口,提供的類有:date,time,datetime,timedelta,tzinfo.
在之前的文章中我們講過:萬字總結!Python 實現定時任務的八種方案
在定時任務中,I want to set up a feature that reminds me after a week.
如果用time模塊進行實現
import time
time.time() + 7*24*60*60 # 7天*24小時*60分鐘*60秒
You need to calculate it yourself7天後的時間戳,而如果使用datetime模塊,This thing is very simple:直接days + 7
,如下圖代碼所示.
import datetime
datetime.datetime.now() + datetime.timedelta(days=7)#格式化時間
Timestamps and structured data、between string data,可以進行轉換.A note on this is shown above,這裡不再贅述,如有疑問,可以添加我的微信,communicate in more detailCoderWanFeng
活動地址:[CSDN21天學習挑戰賽]