python常用內建模組:datetime
阿新 • • 發佈:2019-02-15
使用
匯入datetime模組下的datetime類,如果只是import datetime 那麼呼叫要通過datetime.datetime
舉例:返回當前日期和時間:
>>> from datetime import datetime
>>> now = datetime.now()
>>> print(now)
2018-08-10 10:44:58.169000
>>>
返回的是一個日期型別:
>>> print(type(now))
<class 'datetime.datetime'>
>>>
datetime轉換為timestamp,使用timestamp():
>>> now.timestamp()
1533869098.169 #timestamp是一個浮點數,如果有小數位,小數位表示毫秒數
timestamp轉換為datetime,使用fromtimestamp():
>>> print(datetime.fromtimestamp(1533869098.169))
2018-08-10 10:44:58.169000
str轉換為datetime,使用datetime.strptime():
>>> d = datetime.strptime('2018-8-10 11:00:00' , '%Y-%m-%d %H:%M:%S')
>>> print(d)
2018-08-10 11:00:00
>>>
datetime轉換為str,使用strftime():
>>> from datetime import datetime
>>> now = datetime.now()
>>> n = now.strftime('%Y-%m-%d %H:%M:%S')
>>> print(n)
2018-08-10 10:44:58
datetime的加減,使用timedelta():
>>> from datetime import datetime, timedelta
>>> now = datetime.now()
>>> now
datetime.datetime(2018, 8, 10, 11, 7, 41, 576000)
>>> now + timedelta(hours=1)
datetime.datetime(2018, 8, 10, 12, 7, 41, 576000)
>>> now - timedelta(days=1)
datetime.datetime(2018, 8, 9, 11, 7, 41, 576000)
>>> now + timedelta(days=2, hours=12)
datetime.datetime(2018, 8, 12, 23, 7, 41, 576000)
>>>