2-datetime 模塊

datetime

時間轉字符串

在咱們的使用中,咱們經常須要將時間轉換爲字符串,用來做爲文件的名字或者用於加密字符的輸出等等。例子:加密

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

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

字符轉時間

有時候咱們須要將一個字符給轉換爲時間對象對象

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

時間戳的轉換

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))

加 就是 延後幾秒; 減 就是提早幾秒ip

轉換格式

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

工做中常常須要用到美國時間,作一個記錄。 utc晚了8個小時,因此要減去便是美國時間字符串

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

參考

《The Python3 Standard Library By Example》it

相關文章
相關標籤/搜索