python 下字符串格式时间比较
python 下有多个有关时间的模块,分别是time、datetime、calendar,今天重点讨论下time写法。
其中time模块,主要有以下方法:
ltime=time.time() 获取当前系统时间,返回float型数值时间戳(当前时间相对于1970.1.1 00:00:00以秒计算的偏移量);
localtime=time.localtime(ltime) 把float型时间戳转变成当前时区struct time型时间(其实是一个数组);
localtime=time.gmtime(ltime) 把float型时间戳转变成UTC时区struct time型时间(其实是一个数组);
ltime= time.mktime(localtime) 把str uct time转成float型时间戳。
strtime= time.strftime('%Y%m%d %H%M%S', localtime) ,localtime参数是struct time时间,返回字符串。
localtime=time.strptime(strtime,'%Y%m%d %H%M%S') ,正好是strftime的反向操作,strtime参数字符串格式日期。
举例,一个时间偏移后的比较情况:
1 #-*-coding=utf-8-*- 2 __author__='zhongtang' 3 4 ''' 5 时间戳与字符串的互相转换 6 ''' 7 8 import time 9 10 localtime1=time.localtime() 11 time.sleep(5) 12 localtime2=time.localtime(time.time()) 13 14 print type(localtime1),localtime1 15 print type(localtime2),localtime2 16 17 gmtime=time.gmtime(time.time()) 18 print type(gmtime),gmtime 19 20 21 strtime1='20160518010101' 22 strtime2='20160518020101' 23 24 #字符串变成时间数据结构 25 localtime1=time.strptime(strtime1,'%Y%m%d%H%M%S') 26 localtime2=time.strptime(strtime2,'%Y%m%d%H%M%S') 27 28 print type(localtime1),localtime1 29 print type(localtime2),localtime2 30 31 32 #从时间数据结构转换成时间戳 33 time1= time.mktime(localtime1) 34 time2= time.mktime(localtime2) 35 36 print type(time1),time1 37 print type(time2),time2 38 39 #时间戳可以直接相减,得到以秒为单位的差额 40 print time2-time1
输出结果
1 <type 'time.struct_time'> time.struct_time(tm_year=2016, tm_mon=5, tm_mday=19, tm_hour=9, tm_min=9, tm_sec=30, tm_wday=3, tm_yday=140, tm_isdst=0) 2 <type 'time.struct_time'> time.struct_time(tm_year=2016, tm_mon=5, tm_mday=19, tm_hour=9, tm_min=9, tm_sec=35, tm_wday=3, tm_yday=140, tm_isdst=0) 3 <type 'time.struct_time'> time.struct_time(tm_year=2016, tm_mon=5, tm_mday=19, tm_hour=1, tm_min=9, tm_sec=35, tm_wday=3, tm_yday=140, tm_isdst=0) 4 <type 'time.struct_time'> time.struct_time(tm_year=2016, tm_mon=5, tm_mday=18, tm_hour=1, tm_min=1, tm_sec=1, tm_wday=2, tm_yday=139, tm_isdst=-1) 5 <type 'time.struct_time'> time.struct_time(tm_year=2016, tm_mon=5, tm_mday=18, tm_hour=2, tm_min=1, tm_sec=1, tm_wday=2, tm_yday=139, tm_isdst=-1) 6 <type 'float'> 1463504461.0 7 <type 'float'> 1463508061.0 8 3600.0