Python模組學習筆記— —time與datatime,pythondatatime
Python提供了多個內建模組用於操作日期時間,像calendar,time,datetime。首先對time模組中最常用的幾個函數作一個介紹,它提供的介面與C標準庫time.h基本一致。然後再介紹一下datatime模組,相比於time模組,datetime模組的介面則更直觀、更容易調用。
time模組
time.time
time.time()函數返回從1970年1月1日以來的秒數,這是一個浮點數。
import timeprint time.time()
time.sleep
可以通過調用time.sleep來掛起當前的進程。time.sleep接收一個浮點型參數,參數單位為秒,表示進程掛起的時間。
time.clock
在windows作業系統上,time.clock() 返回第一次調用該方法到現在的秒數,其精確度高於1微秒。可以使用該函數來記錄程式執行的時間。
import timeprint time.clock()time.sleep(2)print time.clock()time.sleep(3)print time.clock()
time.gmtime
該函數原型為:time.gmtime([sec]),可選的參數sec表示從1970-1-1以來的秒數。其預設值為time.time(),函數返回time.struct_time類型的對象(struct_time是在time模組中定義的表示時間的對象)。
import timeprint time.gmtime() print time.gmtime(time.time() - 24 * 60 * 60)
time.localtime
time.localtime與time.gmtime非常類似,也返回一個struct_time對象,可以把它看作是gmtime()的語言版本。
time.mktime
time.mktime執行與gmtime(), localtime()相反的操作,它接收struct_time對象作為參數,返回用秒數來表示時間的浮點數。
import timeprint time.mktime(time.localtime())print time.time()
time.strftime
time.strftime將日期轉換為字串表示,它的函數原型為:time.strftime(format[, t])。參數format是格式字串(格式字串的知識可以參考:time.strftime),可選的參數t是一個struct_time對象。
import timeprint time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())print time.strftime('Weekday: %w; Day of the yesr: %j')
time.strptime
按指定格式解析一個表示時間的字串,返回struct_time對象。該函數原型為:time.strptime(string, format),兩個參數都是字串。
import timeprint time.strptime('201-06-23 15:30:53', '%Y-%m-%d %H:%M:%S')
以上僅僅是time模組中最常用的幾個方法,還有很多其他的方法如:time.timezone, time.tzname …感興趣的童鞋可以參考Python手冊 time 模組
datetime模組
datetime模組定義了兩個常量:datetime.MINYEAR和datetime.MAXYEAR,分別表示datetime所能表示的最小、最大年份。其中,MINYEAR = 1,MAXYEAR = 9999。
datetime模組定義了下面這幾個類:
-datetime.date:表示日期的類。常用的屬性有year, month, day;
-datetime.time:表示時間的類。常用的屬性有hour, minute, second, microsecond;
-datetime.datetime:表示日期時間。
-datetime.timedelta:表示時間間隔,即兩個時間點之間的長度。
-datetime.tzinfo:與時區有關的相關資訊。(這裡不詳細充分討論該類,感興趣的童鞋可以參考python手冊)
【注】上面這些類型的對象都是不可變(immutable)的。
date類
date類表示一個日期。其建構函式如下:
class datetime.date(year, month, day)
year的範圍是[MINYEAR, MAXYEAR],即[1, 9999];
month的範圍是[1, 12];
day的最大值根據給定的year, month參數來決定,閏年2月份有29天。
date類定義了一些常用的類方法與類屬性,方便我們操作:
-date.max、date.min:date對象所能表示的最大、最小日期;
-date.resolution:date對象表示日期的最小單位。這裡是天。
-date.today():返回一個表示當前本地日期的date對象;
-date.fromtimestamp(timestamp):根據給定的時間戮,返回一個date對象;
-datetime.fromordinal(ordinal):將Gregorian日曆時間轉換為date對象;(Gregorian Calendar:一種日曆表示方法,類似於我國的農曆,西方國家使用比較多。)
from datetime import * import time print 'date.max:', date.max print 'date.min:', date.min print 'date.today():', date.today() print 'date.fromtimestamp():', date.fromtimestamp(time.time())
date提供的執行個體方法和屬性:
-date.year、date.month、date.day:年、月、日;
-date.replace(year, month, day):產生一個新的日期對象,用參數指定的年,月,日代替原有對象中的屬性。
-date.timetuple():返回日期對應的time.struct_time對象;
-date.toordinal():返回日期對應的Gregorian Calendar日期;
-date.weekday():返回weekday,如果是星期一,返回0;如果是星期2,返回1,以此類推;
-data.isoweekday():返回weekday,如果是星期一,返回1;如果是星期2,返回2,以此類推;
-date.isocalendar():返回格式如(year,month,day)的元組;
-date.isoformat():返回格式如’YYYY-MM-DD’的字串;
-date.strftime(fmt):自訂格式化字串。
from datetime import * now = date(2015,6,10)tomorrow = now.replace(day = 11)print 'now:',now, ', tomorrow:',tomorrowprint 'timetuple():', now.timetuple()print 'weekday():', now.weekday()print 'isoweekday():', now.isoweekday()print 'isocalendar():', now.isocalendar()print 'isoformat():', now.isoformat()
date還對一些操作進行了重載,允許對日期進行如下一些操作:
-date2 = date1 + timedelta # 日期加上一個間隔,返回一個新的日期對象(timedelta將在下面介紹,表示時間間隔)
-date2 = date1 - timedelta # 日期隔去間隔,返回一個新的日期對象
-timedelta = date1 - date2 # 兩個日期相減,返回一個時間間隔對象
date1 < date2 # 兩個日期進行比較
【注】對日期進行操作時,要防止日期超出它所能表示的範圍。
from datetime import * now = date.today()tomorrow = now.replace(day = 11)delta = tomorrow - nowprint 'now:', now, ' tomorrow:', tomorrowprint 'timedelta:', deltaprint now + deltaprint tomorrow > now
time類
time類表示時間,由時、分、秒以及微秒組成。time類的建構函式如下:
class datetime.time(hour[, minute[, second[, microsecond[, tzinfo]]]])
參數tzinfo表示時區資訊。各參數的取值範圍:hour的範圍為[0, 24),minute的範圍為[0, 60),second的範圍為[0, 60),microsecond的範圍為[0, 1000000)。
time類定義的類屬性:
-time.min、time.max:time類所能表示的最小、最大時間。其中time.min = time(0, 0, 0, 0), time.max = time(23, 59, 59, 999999);
-time.resolution:時間的最小單位,這裡是1微秒;
time類提供的執行個體方法和屬性:
-time.hour、time.minute、time.second、time.microsecond:時、分、秒、微秒;
-time.tzinfo:時區資訊;
-time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]]):建立一個新的時間對象,用參數指定的時、分、秒、微秒代替原有對象中的屬性(原有對象仍保持不變);
-time.isoformat():返回型如”HH:MM:SS”格式的字串表示;
-time.strftime(fmt):返回自訂格式化字串。
from datetime import * tm = time(7, 17, 10) print 'tm:', tm print 'hour: %d, minute: %d, second: %d, microsecond: %d' \ % (tm.hour, tm.minute, tm.second, tm.microsecond)tm1 = tm.replace(hour = 8) print 'tm1:', tm1 print 'isoformat():', tm.isoformat()
像date一樣,time也可以對兩個time對象進行比較,或者相減返回一個時間間隔對象。
datetime類
datetime是date與time的結合體,包括date與time的所有資訊。它的建構函式如下:
datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])
各參數的含義與date、time的建構函式中的一樣,要注意參數值的範圍。
datetime類定義的類屬性與方法:
-datetime.min、datetime.max:datetime所能表示的最小值與最大值;
-datetime.resolution:datetime最小單位;
-datetime.today():返回一個表示當前本地時間的datetime對象;
-datetime.now([tz]):返回一個表示當前本地時間的datetime對象,如果提供了參數tz,則擷取tz參數所指時區的本地時間;
-datetime.utcnow():返回一個當前utc時間的datetime對象;
-datetime.fromtimestamp(timestamp[, tz]):根據時間戮建立一個datetime對象,參數tz指定時區資訊;
-datetime.utcfromtimestamp(timestamp):根據時間戮建立一個datetime對象;
-datetime.combine(date, time):根據date和time,建立一個datetime對象;
-datetime.strptime(date_string, format):將格式字串轉換為datetime對象;
from datetime import * import timeprint 'datetime.max:', datetime.max print 'datetime.min:', datetime.min print 'datetime.resolution:', datetime.resolution print 'today():', datetime.today() print 'now():', datetime.now() print 'utcnow():', datetime.utcnow() print 'fromtimestamp(tmstmp):', datetime.fromtimestamp(time.time()) print 'utcfromtimestamp(tmstmp):', datetime.utcfromtimestamp(time.time())
datetime類提供的執行個體方法與屬性(很多屬性或方法在date和time中已經出現過,可參考上文):
-datetime.year、month、day、hour、minute、second、microsecond、tzinfo:
-datetime.date():擷取date對象;
-datetime.time():擷取time對象;
-datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]]):
-datetime.timetuple()
-datetime.utctimetuple()
-datetime.toordinal()
-datetime.weekday()
-datetime.isocalendar()
-datetime.isoformat([sep])
-datetime.ctime():返回一個日期時間的C格式字串,等效於time.ctime(time.mktime(dt.timetuple()));
datetime.strftime(format)
像date一樣,也可以對兩個datetime對象進行比較,或者相減返回一個時間間隔對象,或者日期時間加上一個間隔返回一個新的日期時間對象。
格式字串
datetime、date、time都提供了strftime()方法,該方法接收一個格式字串,輸出日期時間的字串表示。
| 格式字元 |
意義 |
| %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]) |
| %U |
周在當年的周數當年的第幾周),星期天作為周的第一天 |
| %w |
今天在這周的天數,範圍為[0, 6],6表示星期天 |
| %W |
周在當年的周數(是當年的第幾周),星期一作為周的第一天 |
| %x |
日期文字(如:04/07/10) |
| %X |
時間字串(如:10:43:39) |
| %y |
2個數字表示的年份 |
| %Y |
4個數字表示的年份 |
| %z |
與utc時間的間隔 (如果是本地時間,返回Null 字元串) |
| %Z |
時區名稱(如果是本地時間,返回Null 字元串) |
| %% |
%% => % |
from datetime import * import timedt = 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')