2-datetime 模塊

datetime

時間轉(zhuǎn)字符串

在我們的使用中,我們常常需要將時間轉(zhuǎn)換為字符串,用來作為文件的名字或者用于加密字符的輸出等等。例子:

from datetime import datetime 
datetime.strftime(datetime.now(),"%Y-%m-%d %H:%M:%S")

記憶方式也很簡單,str from time

字符轉(zhuǎn)時間

有時候我們需要將一個字符給轉(zhuǎn)換為時間對象

from datetime import datetime 
>>> datetime.strptime('2018-09-09',"%Y-%m-%d")
datetime.datetime(2018, 9, 9, 0, 0)

時間戳的轉(zhuǎn)換

import time 
from datetime import datetime 
stamp = time.time()
datetime.fromtimestamp(stamp)

timedelta

import datetime
print('microseconds:', datetime.timedelta(microseconds=1))
print('milliseconds:', datetime.timedelta(milliseconds=1))
print('seconds :', datetime.timedelta(seconds=1))
print('minutes :', datetime.timedelta(minutes=1))
print('hours :', datetime.timedelta(hours=1))
print('days :', datetime.timedelta(days=1))
print('weeks :', datetime.timedelta(weeks=1))

加 就是 延后幾秒; 減 就是提前幾秒

轉(zhuǎn)換格式

Symbol Meaning Example
%a Abbreviated weekday name 'Wed'
%A Full weekday name 'Wednesday'
%w Weekday number: 0 (Sunday) through 6 (Saturday) '3'
%d Day of the month (zero padded) '13'
%b Abbreviated month name 'Jan'
%B Full month name 'January'
%m Month of the year '01'
%y Year without century '18'
%Y Year with century '2018'
%H Hour from 24-hour clock '17'
%I Hour from 12-hour clock '05'
%p AM/PM 'PM'
%M Minutes '00'
%S Seconds '00'
%f Microseconds '000000'
%z UTC offset for time zone–aware objects '-0500'
%Z Time zone name 'EST'
%j Day of the year '013'
%W Week of the year '02'
%c Date and time representation for the current locale 'Wed Jan 13 17:00:00 2016'
%x Date representation for the current locale '01/13/16'
%X Time representation for the current locale '17:00:00'
%% A literal % character '%'

tips

工作中經(jīng)常需要用到美國時間,做一個記錄。 utc晚了8個小時,所以要減去即是美國時間

datetime.strftime(datetime.utcnow()-timedelta(hours=8),'%Y-%m-%d %H:%M:%S')

GMT時間格式

GMT_FORMAT =  '%a, %d %b %Y %H:%M:%S GMT'

參考

《The Python3 Standard Library By Example》

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容