Python 基礎 - 4.1 time模組

來源:互聯網
上載者:User

標籤:res   min   時間處理   oat   有關   nta   python   ica   zone   

time & datetime 模組

在平常的代碼中,我們常常需要與時間打交道。在Python中,與時間處理有關的模組就包括:time,datetime,calendar(很少用,不講),下面分別來介紹。

在開始之前,首先要說明幾點:

一、在Python中,通常有這幾種方式來表示時間:

  1. 時間戳記
  2. 格式化的時間字串
  3. 元組(struct_time)共九個元素。由於Python的time模組實現主要調用C庫,所以各個平台可能有所不同。

二、幾個定義

UTC(Coordinated Universal Time,世界協調時)亦即格林威治天文時間,世界標準時間。在中國為UTC+8。DST(Daylight Saving Time)即夏令時。

時間戳記(timestamp)的方式:通常來說,時間戳記表示的是從1970年1月1日00:00:00開始按秒計算的位移量。我們運行“type(time.time())”,返回的是float類型。

元組(struct_time)方式:struct_time元組共有9個元素,返回struct_time的函數主要有gmtime(),localtime(),strptime()。下面列出這種方式元組中的幾個元素:

索引(Index)    屬性(Attribute)    值(Values)0     tm_year(年)                 比如2011 1     tm_mon(月)             1 - 122     tm_mday(日)                 1 - 313     tm_hour(時)                 0 - 234     tm_min(分)             0 - 595     tm_sec(秒)             0 - 616     tm_wday(weekday)            0 - 6(0表示周日)7     tm_yday(一年中的第幾天)    1 - 3668     tm_isdst(是否是夏令時)            預設為-1
time模組的方法
  • time.localtime([secs]):將一個時間戳記轉換為當前時區的struct_time。secs參數未提供,則以目前時間為準。
  • time.gmtime([secs]):和localtime()方法類似,gmtime()方法是將一個時間戳記轉換為UTC時區(0時區)的struct_time。
  • time.time():返回目前時間的時間戳記。
  • time.mktime(t):將一個struct_time轉化為時間戳記。
  • time.sleep(secs):線程延遲指定的時間運行。單位為秒。
  • time.asctime([t]):把一個表示時間的元組或者struct_time表示為這種形式:‘Sun Oct 1 12:04:38 2017‘。如果沒有參數,將會將time.localtime()作為參數傳入。
  • time.ctime([secs]):把一個時間戳記(按秒計算的浮點數)轉化為time.asctime()的形式。如果參數未給或者為None的時候,將會預設time.time()為參數。它的作用相當於time.asctime(time.localtime(secs))。
  • time.strftime(format[, t]):把一個代表時間的元組或者struct_time(如由time.localtime()和time.gmtime()返回)轉化為格式化的時間字串。如果t未指定,將傳入time.localtime()。

    • 舉例:time.strftime("%Y-%m-%d %X", time.localtime()) #輸出‘2017-10-01 12:14:23‘
  • time.strptime(string[, format]):把一個格式化時間字串轉化為struct_time。實際上它和strftime()是逆操作。

    • 舉例:time.strptime(‘2017-10-3 17:54‘,"%Y-%m-%d %H:%M") #輸出 time.struct_time(tm_year=2017, tm_mon=10, tm_mday=3, tm_hour=17, tm_min=54, tm_sec=0, tm_wday=1, tm_yday=276, tm_isdst=-1)
字串轉時間格式對應表
 
  Meaning Notes
%a Locale’s abbreviated weekday name.  
%A Locale’s full weekday name.  
%b Locale’s abbreviated month name.  
%B Locale’s full month name.  
%c Locale’s appropriate date and time representation.  
%d Day of the month as a decimal number [01,31].  
%H Hour (24-hour clock) as a decimal number [00,23].  
%I Hour (12-hour clock) as a decimal number [01,12].  
%j Day of the year as a decimal number [001,366].  
%m Month as a decimal number [01,12].  
%M Minute as a decimal number [00,59].  
%p Locale’s equivalent of either AM or PM. (1)
%S Second as a decimal number [00,61]. (2)
%U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. (3)
%w Weekday as a decimal number [0(Sunday),6].  
%W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. (3)
%x Locale’s appropriate date representation.  
%X Locale’s appropriate time representation.  
%y Year without century as a decimal number [00,99].  
%Y Year with century as a decimal number.  
%z Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].  
%Z Time zone name (no characters if no time zone exists).  
  %% A literal‘%‘character.

最後為了容易記住轉換關係,看

 

 datetime模組

相比於time模組,datetime模組的介面則更直觀、更容易調用

datetime模組定義了下面這幾個類:

  • datetime.date:表示日期的類。常用的屬性有year, month, day;
  • datetime.time:表示時間的類。常用的屬性有hour, minute, second, microsecond;
  • datetime.datetime:表示日期時間。
  • datetime.timedelta:表示時間間隔,即兩個時間點之間的長度。
  • datetime.tzinfo:與時區有關的相關資訊。(這裡不詳細充分討論該類,感興趣的童鞋可以參考python手冊)

我們需要記住的方法僅以下幾個:

  1. d=datetime.datetime.now() 返回當前的datetime日期類型
d.timestamp(),d.today(), d.year,d.timetuple()等方法可以調用

2.datetime.date.fromtimestamp(322222) 把一個時間戳記轉為datetime日期類型

3.時間運算

>>> datetime.datetime.now()datetime.datetime(2017, 10, 1, 12, 53, 11, 821218)>>> datetime.datetime.now() + datetime.timedelta(4) #目前時間 +4天datetime.datetime(2017, 10, 5, 12, 53, 35, 276589)>>> datetime.datetime.now() + datetime.timedelta(hours=4) #目前時間+4小時datetime.datetime(2017, 10, 1, 16, 53, 42, 876275)

4.時間替換

>>> d.replace(year=2999,month=11,day=30)datetime.date(2999, 11, 30)


In [1]: import timeIn [2]: time.localtime()Out[2]: time.struct_time(tm_year=2018, tm_mon=1, tm_mday=25, tm_hour=18, tm_min=40, tm_sec=21, tm_wday=3, tm_yday=25, tm_isdst=0)
In [5]: a = time.localtime()In [6]: aOut[6]: time.struct_time(tm_year=2018, tm_mon=1, tm_mday=25, tm_hour=18, tm_min=41, tm_sec=17, tm_wday=3, tm_yday=25, tm_isdst=0)In [7]: a.a.count              a.tm_hour            a.tm_wdaya.index              a.tm_isdst           a.tm_ydaya.n_fields           a.tm_mday            a.tm_yeara.n_sequence_fields  a.tm_min             a.tm_zonea.n_unnamed_fields   a.tm_mon             a.tm_gmtoff          a.tm_sec             In [7]: a.tm_yearOut[7]: 2018In [8]: ‘%s-%s-%s‘ % (a.tm_year,a.tm_mon,a.tm_)a.tm_gmtoff  a.tm_mday    a.tm_sec     a.tm_yeara.tm_hour    a.tm_min     a.tm_wday    a.tm_zonea.tm_isdst   a.tm_mon     a.tm_yday    In [8]: ‘%s-%s-%s‘ % (a.tm_year,a.tm_mon,a.tm_mday)Out[8]: ‘2018-1-25‘

 

 

Python 基礎 - 4.1 time模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.