1. 程式人生 > >【python】 time模塊和datetime模塊詳解 【轉】

【python】 time模塊和datetime模塊詳解 【轉】

-a cond .com ima 封裝 基本 sta times %d

一、time模塊

time模塊中時間表現的格式主要有三種:

  a、timestamp時間戳,時間戳表示的是從1970年1月1日00:00:00開始按秒計算的偏移量

  b、struct_time時間元組,共有九個元素組。

  c、format time 格式化時間,已格式化的結構使時間更具可讀性。包括自定義格式和固定格式。

1、時間格式轉換圖:

技術分享圖片

2、主要time生成方法和time格式轉換方法實例:

 1 import time
 2 
 3 #【生成timestamp時間戳】
 4 print(time.time())
 5 print(time.mktime(time.localtime())) #
struct_time to timestamp 6 print(-*20) 7 8 # 【生成struct_time時間元組】 9 # timestamp to struct_time 【本地時間】 10 print(time.localtime()) 11 print(time.localtime(time.time())) 12 print(-*20) 13 # timestamp to struct_time 【格林威治時間】 14 print(time.gmtime()) 15 print(time.gmtime(time.time())) 16 print(-*20)
17 #format_time(格式化時間) to struct_time(時間元組) 18 print(time.strptime(2014-11-11, %Y-%m-%d)) 19 print(time.strptime(2011-05-05 16:37:06, %Y-%m-%d %X)) 20 print(-*20)

struct_time元組元素結構

屬性                            值
tm_year(年)                  比如2011 
tm_mon(月)                   1 - 12
tm_mday(日)                  
1 - 31 tm_hour(時) 0 - 23 tm_min(分) 0 - 59 tm_sec(秒) 0 - 61 tm_wday(weekday) 0 - 6(0表示周日) tm_yday(一年中的第幾天) 1 - 366 tm_isdst(是否是夏令時) 默認為-1

format time結構化表示

格式 含義
%a 本地(locale)簡化星期名稱
%A 本地完整星期名稱
%b 本地簡化月份名稱
%B 本地完整月份名稱
%c 本地相應的日期和時間表示
%d 一個月中的第幾天(01 - 31)
%H 一天中的第幾個小時(24小時制,00 - 23)
%I 第幾個小時(12小時制,01 - 12)
%j 一年中的第幾天(001 - 366)
%m 月份(01 - 12)
%M 分鐘數(00 - 59)
%p 本地am或者pm的相應符
%S 秒(01 - 61)
%U 一年中的星期數。(00 - 53星期天是一個星期的開始。)第一個星期天之前的所有天數都放在第0周。
%w 一個星期中的第幾天(0 - 6,0是星期天)
%W 和%U基本相同,不同的是%W以星期一為一個星期的開始。
%x 本地相應日期
%X 本地相應時間
%y 去掉世紀的年份(00 - 99)
%Y 完整的年份
%Z 時區的名字(如果不存在為空字符)
%% ‘%’字符

常見結構化時間組合:

print time.strftime("%Y-%m-%d %X")
#2018-9-5 14:50:13

3、time加減

1 #timestamp加減單位以秒為單位
2 import time
3 t1 = time.time()
4 t2=t1+10
5 
6 print time.ctime(t1)#Wed Oct 26 21:15:30 2018
7 print time.ctime(t2)

二、datetime模塊

datatime模塊重新封裝了time模塊,提供更多接口,提供的類有:date,time,datetime,timedelta,tzinfo。

1、date類

 1 from  datetime import *
 2 import time
 3 # 【靜態方法和字段】
 4 print(date.max) #對象所能表示的最大、最小日期
 5 print(date.min)
 6 print(date.resolution)#對象表示日期的最小單位。這裏是天
 7 print(date.today()) #返回一個表示當前本地日期的date對象
 8 print(date.fromtimestamp(time.time())) #根據給定的時間戮,返回一個date對象;
 9 
10 # 【方法和屬性】
11 now = date(2018, 9, 5)
12 tomorrow = now.replace(day = 27)
13 
14 print(now.replace(2012,8,8)) #生成一個新的日期對象,用參數指定的年,月,日代替原有對象中的屬性。
15 print(now,tomorrow)
16 print(-*20)
17 
18 print(now.timetuple()) #返回日期對應的time.struct_time對象;
19 print(-*20)
20 
21 print(now.weekday()) #返回weekday,如果是星期一,返回0;如果是星期2,返回1,以此類推;
22 print(now.isoweekday()) #返回weekday,如果是星期一,返回1;如果是星期2,返回2,以此類推;
23 print(-*20)
24 
25 print(now.isocalendar()) #返回格式如(year,month,day)的元組;
26 print(now.isoformat()) #返回格式如‘YYYY-MM-DD’的字符串;
27 print(now.strftime("%Y-%m-%d"))

2、time類

1 from  datetime import *
2 tm = time(23,46,10)
3 print(tm)
4 print(hour: %d, minute: %d, second: %d, microsecond: %d % (tm.hour, tm.minute, tm.second, tm.microsecond))
5 tm1 = tm.replace(hour=20)
6 print(tm1:, tm1)
7 print(isoformat:, tm.isoformat())
8 print(strftime, tm.strftime("%X"))

3、datetime類

 1 # 靜態方法和字段
 2 from  datetime import *
 3 import time
 4 
 5 print(datetime.max:, datetime.max)
 6 print(datetime.min:, datetime.min)
 7 print(datetime.resolution:, datetime.resolution)
 8 print(-*20)
 9 print(today():, datetime.today())
10 print(now():, datetime.now())
11 print(utcnow():, datetime.utcnow())
12 print(-*20)
13 print(fromtimestamp(tmstmp):, datetime.fromtimestamp(time.time()))
14 print(utcfromtimestamp(tmstmp):, datetime.utcfromtimestamp(time.time()))
15 
16 # 方法和屬性
17 dt=datetime.now()#datetime對象
18 print(dt.date())
19 print(dt.time())
20 print(dt.replace())
21 print(-*20)
22 print(dt.timetuple())
23 print(dt.utctimetuple())
24 print(-*20)
25 print(dt.toordinal())
26 print(dt.weekday())
27 print(-*20)
28 print(dt.isocalendar())
29 print(dt.ctime())
30 print(dt.strftime)

4.timedelta類,時間加減

 1 from  datetime import *
 2 
 3 dt = datetime.now()
 4 
 5 dt1 = dt + timedelta(days=-1)#昨天
 6 dt2 = dt - timedelta(days=1)#昨天
 7 dt3 = dt + timedelta(days=1)#明天
 8 delta_obj = dt3-dt1
 9 
10 print(type(delta_obj),delta_obj)
11 print(delta_obj.days,delta_obj.total_seconds())

5、tzinfo時區類

 1 from datetime import datetime, tzinfo,timedelta
 2 
 3 """
 4 tzinfo是關於時區信息的類
 5 tzinfo是一個抽象類,所以不能直接被實例化
 6 """
 7 class UTC(tzinfo):
 8     def __init__(self,offset = 0):
 9         self._offset = offset
10 
11     def utcoffset(self, dt):
12         return timedelta(hours=self._offset)
13 
14     def tzname(self, dt):
15         return "UTC +%s" % self._offset
16 
17     def dst(self, dt):
18         return timedelta(hours=self._offset)
19 
20 #北京時間
21 beijing = datetime(2011,11,11,0,0,0,tzinfo = UTC(8))
22 print ("beijing time:",beijing)
23 #曼谷時間
24 bangkok = datetime(2011,11,11,0,0,0,tzinfo = UTC(7))
25 print ("bangkok time",bangkok)
26 #北京時間轉成曼谷時間
27 print ("beijing-time to bangkok-time:",beijing.astimezone(UTC(7)))
28 
29 #計算時間差時也會考慮時區的問題
30 timespan = beijing - bangkok
31 print ("時差:",timespan)

【python】 time模塊和datetime模塊詳解 【轉】