python中的time和datetime模塊是時間方面的模塊python
time模塊中時間表現的格式主要有三種:app
一、timestamp:時間戳,時間戳表示的是從1970年1月1日00:00:00開始按秒計算的偏移量post
二、struct_time:時間元組,共有九個元素組。ui
三、format time :格式化時間,已格式化的結構使時間更具可讀性。包括自定義格式和固定格式。spa
一、時間格式轉換圖:3d
二、主要time生成方法和time格式轉換方法實例:code
生成timestamp(時間戳)orm
1 >>> 2 >>> import time 3 >>> time.time() 4 1491631287.1797802 5 >>> #由struct_time生成timestamp 6 >>> time.mktime(time.localtime()) 7 1491631461.0 #後面始終都是一位小數,0 ? 8 >>>
生成struct_time (時間元組)對象
1 >>> #直接生成時間元組 2 >>> time.localtime() 3 time.struct_time(tm_year=2017, tm_mon=4, tm_mday=8, tm_hour=14, tm_min=7, tm_sec=20, tm_wday=5, tm_yday=98, tm_isdst=0) 4 >>> #把時間戳轉換爲時間元組 5 >>> time.localtime(time.time()) 6 time.struct_time(tm_year=2017, tm_mon=4, tm_mday=8, tm_hour=14, tm_min=8, tm_sec=5, tm_wday=5, tm_yday=98, tm_isdst=0) 7 >>> #把localtime()換爲gmtime() 就表示格林威治時間 8 >>> 9 >>> #把格式化時間轉換爲時間元組 10 >>> time.strptime('2017-4-8 14:12:12','%Y-%m-%d %X') 11 time.struct_time(tm_year=2017, tm_mon=4, tm_mday=8, tm_hour=14, tm_min=12, tm_sec=12, tm_wday=5, tm_yday=98, tm_isdst=-1) 12 >>> time.strptime('2017-4-8','%Y-%m-%d') 13 time.struct_time(tm_year=2017, tm_mon=4, tm_mday=8, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=98, tm_isdst=-1) 14 >>>
屬性 值
tm_year(年) 好比2017 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 (格式化時間)blog
1 >>> 2 >>> #直接生成format_time 3 >>> time.strftime('%Y-%m-%d %X') 4 '2017-04-08 14:16:11' 5 >>> 6 >>> #把struct_time轉換爲format_time 7 >>> time.strftime('%Y-%m-%d %X',time.localtime()) 8 '2017-04-08 14:17:30' 9 >>>
%Y 年 Year with century as a decimal number.
%m 月 Month as a decimal number [01,12].
%d 日 Day of the month as a decimal number [01,31].
%H 時 Hour (24-hour clock) as a decimal number [00,23].
%M 分 Minute as a decimal number [00,59].
%S 秒 Second as a decimal number [00,61].
%z Time zone offset from UTC.
%a 周幾簡寫(英文Sun) Locale's abbreviated weekday name.
%A 周幾全名(英文Sunday) Locale's full weekday name.
%b 月份簡寫(英語Apr) Locale's abbreviated month name.
%B 月份全名(英語April) Locale's full month name.
%c Locale's appropriate date and time representation.
%I 十二小時制小時數 Hour (12-hour clock) as a decimal number [01,12].
%p AM/PM Locale's equivalent of either AM or PM.
%X 本地相應時間
%x 本地相應日期
生成固定格式的時間表示格式
1 >>> time.asctime() 2 'Sat Apr 8 14:20:04 2017' 3 >>> 4 >>> time.ctime() 5 'Sat Apr 8 14:20:09 2017' 6 >>> 7 >>> time.asctime(time.localtime()) 8 'Sat Apr 8 14:20:27 2017' 9 >>> 10 >>> time.ctime(time.time()) 11 'Sat Apr 8 14:20:44 2017'
1 >>> 2 >>> #timestamp加減是以秒爲單位 3 >>> import time 4 >>> t1 = time.time() 5 >>> t2 = t1 + 10 6 >>> t1 7 1491634614.3497803 8 >>> t2 9 1491634624.3497803 10 >>>
datatime模塊從新封裝了time模塊,提供更多接口,提供的類有:date,time,datetime,timedelta,tzinfo。
一、date類
datetime.date(year, month, day)
靜態方法和字段
date.max、date.min:date對象所能表示的最大、最小日期; date.resolution:date對象表示日期的最小單位。這裏是天。 date.today():返回一個表示當前本地日期的date對象; date.fromtimestamp(timestamp):根據給定的時間戮,返回一個date對象;
1 >>> import datetime 2 >>> datetime.date.max 3 datetime.date(9999, 12, 31) 4 >>> datetime.date.min 5 datetime.date(1, 1, 1) 6 >>> datetime.date.resolution 7 datetime.timedelta(1) 8 >>> datetime.date.today() 9 datetime.date(2017, 4, 8) 10 >>> datetime.date.fromtimestamp(time.time()) 11 datetime.date(2017, 4, 8) 12 >>>
方法和屬性
d1 = date(2017,4,8) #date對象(年月日都不能是以0開頭 (2017,04,08)錯誤 )
>>> d1 = datetime.date(2017,4,8) >>> d1 datetime.date(2017, 4, 8) >>> d1.year 2017 >>> d1.month 4 >>> d1.day 8 >>>
d1.replace(year, month, day):生成一個新的日期對象,用參數指定的年,月,日代替原有對象中的屬性。(原有對象仍保持不變)
>>> d2 = d1.replace(2017,3,20) >>> d1 datetime.date(2017, 4, 8) >>> d2 datetime.date(2017, 3, 20) >>>
d1.timetuple():返回日期對應的time.struct_time對象;
>>> d1.timetuple() time.struct_time(tm_year=2017, tm_mon=4, tm_mday=8, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=98, tm_isdst=-1) >>>
d1.weekday():返回weekday,若是是星期一,返回0;若是是星期2,返回1,以此類推;
>>> d1.weekday() 5 #週六 >>>
d1.isoweekday():返回weekday,若是是星期一,返回1;若是是星期2,返回2,以此類推;
>>> d1.isoweekday() 6 #週六 weekday鏡像? >>>
d1.isocalendar():返回格式如(year,sum_week,day)的元組;
>>> d1 datetime.date(2017, 4, 8) >>> d1.isocalendar() (2017, 14, 6) #第一個是2017年, 14是 當前爲今年的第14周 6 表示 第14周結束後過了6天(當前是15周) >>>
d1.isoformat():返回格式如'YYYY-MM-DD’的字符串;
>>> d1.isoformat() '2017-04-08' >>>
d1.strftime(fmt):和time模塊format相同。
>>> d1.strftime('%Y-%m-%d') '2017-04-08' >>>
二、time類
datetime.time(hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] )
靜態方法和字段
time.min、time.max:time類所能表示的最小、最大時間
>>> import datetime >>> datetime.time.min datetime.time(0, 0) >>> datetime.time.max datetime.time(23, 59, 59, 999999) >>>
time.resolution:時間的最小單位,這裏是1微秒;
>>> datetime.time.resolution datetime.timedelta(0, 0, 1) #秒,毫秒,微秒 >>>
方法和屬性
t1 = datetime.time(10,23,15) #time對象 時,分,秒...
t1.hour、t1.minute、t1.second、t1.microsecond:時、分、秒、微秒;
>>> t = datetime.time(15,30,20) >>> t datetime.time(15, 30, 20) >>> t.hour 15 >>> t.minute 30 >>> t.second 20 >>> t.microsecond 0 >>>
t1.tzinfo:時區信息;
t1.replace([ hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] ] ):建立一個新的時間對象,用參數指定的時、分、秒、微秒代替原有對象中的屬性
(原有對象仍保持不變);
t1.isoformat():返回型如"HH:MM:SS"格式的字符串表示;
t1.strftime(fmt):同time模塊中的format;
三、datetime類
datetime至關於date和time結合起來。
datetime.datetime (year, month, day[ , hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] ] )
靜態方法和字段
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對象;
方法和屬性
dt=datetime.now()#datetime對象 dt.year、month、day、hour、minute、second、microsecond、tzinfo: dt.date():獲取date對象; dt.time():獲取time對象; dt. replace ([ year[ , month[ , day[ , hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] ] ] ] ]): dt. timetuple () dt. utctimetuple () dt. toordinal () dt. weekday () dt. isocalendar () dt. isoformat ([ sep] ) dt. ctime ():返回一個日期時間的C格式字符串,等效於time.ctime(time.mktime(dt.timetuple())); dt. strftime (format)
4.timedelta類,時間加減
使用timedelta能夠很方便的在日期上作天days,小時hour,分鐘,秒,毫秒,微妙的時間計算,若是要計算月份則須要另外的辦法。
1 >>> import datetime 2 >>> d = datetime.datetime.now() 3 >>> d 4 datetime.datetime(2017, 4, 8, 15, 42, 1, 656144) 8 >>> d1 = d + datetime.timedelta(days=-1) #昨天 9 >>> d1 10 datetime.datetime(2017, 4, 7, 15, 42, 1, 656144) 11 >>> d2 = d - datetime.timedelta(days=1) #昨天 12 >>> d2 13 datetime.datetime(2017, 4, 7, 15, 42, 1, 656144) 14 >>> d3 = d + datetime.timedelta(days=1) #明天 15 >>> d3 16 datetime.datetime(2017, 4, 9, 15, 42, 1, 656144) 17 >>>
五、tzinfo時區類
#! /usr/bin/python # coding=utf-8 from datetime import datetime, tzinfo,timedelta """ tzinfo是關於時區信息的類 tzinfo是一個抽象類,因此不能直接被實例化 """ class UTC(tzinfo): """UTC""" def __init__(self,offset = 0): self._offset = offset def utcoffset(self, dt): return timedelta(hours=self._offset) def tzname(self, dt): return "UTC +%s" % self._offset def dst(self, dt): return timedelta(hours=self._offset) #北京時間 beijing = datetime(2011,11,11,0,0,0,tzinfo = UTC(8)) print "beijing time:",beijing #曼谷時間 bangkok = datetime(2011,11,11,0,0,0,tzinfo = UTC(7)) print "bangkok time",bangkok #北京時間轉成曼谷時間 print "beijing-time to bangkok-time:",beijing.astimezone(UTC(7)) #計算時間差時也會考慮時區的問題 timespan = beijing - bangkok print "時差:",timespan #Output================== # beijing time: 2011-11-11 00:00:00+08:00 # bangkok time 2011-11-11 00:00:00+07:00 # beijing-time to bangkok-time: 2011-11-10 23:00:00+07:00 # 時差: -1 day, 23:00:00