1. 程式人生 > >Python 基礎 - 4.1 time模塊

Python 基礎 - 4.1 time模塊

ati oca nbsp 時間間隔 mtime mon field 包括 values

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 - 12
2     tm_mday(日)                 1 - 31
3     tm_hour(時)                 0 - 23
4     tm_min(分)             0 - 59
5     tm_sec(秒)             0 - 61
6     tm_wday(weekday)            0 - 6(0表示周日)
7     tm_yday(一年中的第幾天)    1 - 366
8     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)
字符串轉時間格式對應表
MeaningNotes
%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 time

In [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]: a
Out[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_wday
a.index              a.tm_isdst           a.tm_yday
a.n_fields           a.tm_mday            a.tm_year
a.n_sequence_fields  a.tm_min             a.tm_zone
a.n_unnamed_fields   a.tm_mon             
a.tm_gmtoff          a.tm_sec             

In [7]: a.tm_year
Out[7]: 2018

In [8]: %s-%s-%s % (a.tm_year,a.tm_mon,a.tm_)
a.tm_gmtoff  a.tm_mday    a.tm_sec     a.tm_year
a.tm_hour    a.tm_min     a.tm_wday    a.tm_zone
a.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模塊