python datetime處理時間

2021-08-01 23:16:11 字數 2227 閱讀 9240

datetime、date、time都提供了strftime()方法,該方法接收乙個格式字串,輸出日期時間的字串表示。下表是從python手冊中拉過來的,我對些進行了簡單的翻譯(翻譯的有點噢口~~)。

格式字元  意義 %a

星期的簡寫。如 星期三為web

%a星期的全寫。如 星期三為wednesday

%b月份的簡寫。如4月份為apr

%b月份的全寫。如4月份為april

%c: 

日期時間的字串表示。(如: 04/07/10 10:43:39)

%d: 

日在這個月中的天數(是這個月的第幾天)

%f: 

微秒(範圍[0,999999])

%h: 

小時(24小時制,[0, 23])

%i: 

小時(12小時制,[0, 11])

%j: 

日在年中的天數 [001,366](是當年的第幾天)

%m: 

月份([01,12])

%m: 

分鐘([00,59])

%p: 

am或者pm

%s: 

秒(範圍為[00,61],為什麼不是[00, 59],參考python手冊~_~)

%u: 

周在當年的週數當年的第幾周),星期天作為周的第一天

%w: 

今天在這週的天數,範圍為[0, 6],6表示星期天

%w: 

周在當年的週數(是當年的第幾周),星期一作為周的第一天

%x: 

日期字串(如:04/07/10)

%x: 

時間字串(如:10:43:39)

%y: 

2個數字表示的年份

%y: 

4個數字表示的年份

%z: 

與utc時間的間隔 (如果是本地時間,返回空字串)

%z: 

時區名稱(如果是本地時間,返回空字串)

%%: 

%% => %

例子:

from  datetime  import  *  

import  time

dt = datetime.now()  

print

'(%y-%m-%d %h:%m:%s %f): ' , dt.strftime( '%y-%m-%d %h:%m:%s %f' )  

print

'(%y-%m-%d %h:%m:%s %p): ' , dt.strftime( '%y-%m-%d %i:%m:%s %p' )  

print

'%%a: %s '  % dt.strftime( '%a' )  

print

'%%a: %s '  % dt.strftime( '%a' )  

print

'%%b: %s '  % dt.strftime( '%b' )  

print

'%%b: %s '  % dt.strftime( '%b' )  

print

'日期時間%%c: %s '  % dt.strftime( '%c' )  

print

'日期%%x:%s '  % dt.strftime( '%x' )  

print

'時間%%x:%s '  % dt.strftime( '%x' )  

print

'今天是這週的第%s天 '  % dt.strftime( '%w' )  

print

'今天是今年的第%s天 '  % dt.strftime( '%j' )  

print

'今周是今年的第%s周 '  % dt.strftime( '%u' )  

# # ---- 結果 ----

# (%y-%m-%d %h:%m:%s %f):  2010-04-07 10:52:18 937000

# (%y-%m-%d %h:%m:%s %p):  10-04-07 10:52:18 am

# %a: wed 

# %a: wednesday 

# %b: apr 

# %b: april 

# 日期時間%c: 04/07/10 10:52:18 

# 日期%x:04/07/10 

# 時間%x:10:52:18 

# 今天是這週的第3天 

# 今天是今年的第097天 

# 今周是今年的第14周

python datetime學習筆記

import datetime d datetime.date 2016,7,24 新建乙個日期,注意前面的0不能有 print d 20106 07 24 d datetime.date.today 獲取當前日期 print d print d.year,d.month,d.day print d...

Python datetime模組小結

模組小結如下 另外有time模組小結 from datetime import date,time,datetime,timedelta datetime.now 當前日期元組 datetime.today 當前日期元組 d1 2018 05 09 10 20 15 d2 2018 06 02 08...

Python datetime模組詳解

1.獲取當前時間 print datetime.now 獲取當前的時間,如果是中國則是北京時間 print datetime.utcnow 獲取utc標準時間,美國格林威治時間執行結果 2018 09 30 15 44 23.884841 2018 09 30 07 44 23.884841 2.時...