Python之时间处理模块time

jopen 10年前

一、简述

  time模块下有两种时间表示方法,一种是:时间戳的方式,是基于1970年1月1日0时0分0秒的偏移,第二种方式是struct_time()类型的表示方法。

---------------------------------------------------------------------------------

二、详情

首先当然是要import一下time模块:

import time
之后我们介绍该模块下的几个常用函数

1. time.time()               返回自1970年1月1日到目前为止的秒数,即所谓的时间戳,是一个浮点数。我对此表示怀疑,所以type一下,果然是浮点数:

<pre code_snippet_id="256309" snippet_file_name="blog_20140325_2_9703352" name="code" class="python">type(time.time())</pre>对于高档的攻城狮而言,记住1970年1月1日是应该的,就像你应该知道1949年10月1日一样。

2. time.sleep()            用于挂起当前线程,它接受一个浮点数,表示挂起时间,单位是秒。比如:

<pre code_snippet_id="256309" snippet_file_name="blog_20140325_3_9735589" name="code" class="python">time.sleep(2.5) #将当前线程挂起2.5秒,休息2.5秒,让子弹再飞一会儿吧</pre>

 

3. time.clock()             用于返回第一次调用该方法到现在的秒数,传说可精确到微妙,我对此很怀疑,测试一下,至少在windows上是不那么靠谱的,测试一下:</span>

<pre code_snippet_id="256309" snippet_file_name="blog_20140325_4_1752694" name="code" class="python">import time time.clock() time.sleep(1.2) print time.clock()</pre>

 

4. time.gmtime([sec])    可选参数[sec]表示自1970年1月1日以来的秒数,默认值是time.time(),即当前的累积秒数,此函数返回一个time.struct_time类型对象,这个对象包括年份,日月,星期,天数,时分秒等描述时间的信息。</span>

<pre code_snippet_id="256309" snippet_file_name="blog_20140325_5_4849593" name="code" class="python">import time time.gmtime() #返回当前时间对应的time_struct类型对象 time.gmtime(time.time()-246060) #返回昨天此时对应的time_struct对象</pre>

5.  time.localtime()    和time.gmtime()一样,刚开始我打印time.gmtime()发现时间上不对,结果发现还有个time.localtime(),试一下这个就对上了,原来localtime才是返回本地时间对应的一个time_struct对象的,而gmtime()大概就是返回一个国际标准时间对应的struct_time对象吧!

6.  time.mktime() 和上述两个函数的操作相反,用于将structt_time对象转换为累加秒数,可这样测试一下,他们的结果应该大致相当

<pre code_snippet_id="256309" snippet_file_name="blog_20140325_6_9621345" name="code" class="python">import time print time.time() print time.mktime(time.localtime()) print time.mktime(time.gmtime())</pre>

7.  time.strftime() 将时间按照给定格式解释为时间字符串,函数原型为:time.strftime(format [,t])  其中t为一个struct_time对象,至于你想要得格式可按照你的要求自由组合,但就像C中的printf函数一样,用%控制符来控制

<pre code_snippet_id="256309" snippet_file_name="blog_20140325_7_7353071" name="code" class="python">import time print time.strftime('%Y-%m-%d %H:%M:%S') print time.strftime('%w,%j',time.gmtime())</pre>

可总结下这些百分号控制符的用法,如下:

%Y 对应年份四位数表示    
%y  对应年份两位数表示            
%m 对应月份          
%d  对应日期                      
%H 对应时间 24小时制      
 %I 对应时间12小时制                
%M 对应分钟          
%S  对应秒钟                      
%j   对应一年中的第几天  
%w  对应星期                                
%W一年中的星期数 

8. time.strptime()将时间字符串解释为一个struct_time对象,它接收两个字符串参数,用法如下示例:

<pre code_snippet_id="256309" snippet_file_name="blog_20140325_12_6461849" name="code" class="python">import time print time.strptime('2009-06-23 15:30:53', '%Y-%m-%d %H:%M:%S')</pre>
9. time.ctime()将一个时间戳转换成一个字符串,默认为当前时间戳</span>