python的學習筆記之——time模塊常用內置函數


1、Python time time()方法

Python time time() 返回當前時間的時間戳(1970紀元后經過的浮點秒數)。

time()方法語法:

time.time()

舉例:

#!/usr/bin/python
import time;
print time.time();

輸出:

1513913514.53

2、Python time localtime()方法

Python time localtime() 函數類似gmtime(),作用是格式化時間戳為本地的時間。 如果sec參數未輸入,則以當前時間為轉換標准。 DST (Daylight Savings Time) flag (-1, 0 or 1) 是否是夏令時。

localtime()方法語法:

time.localtime([ sec ])

舉例:

#!/usr/bin/python
import time

print time.localtime();
print time.localtime(time.time());

輸出:

time.struct_time(tm_year=2017, tm_mon=12, tm_mday=22, tm_hour=11, tm_min=42, tm_sec=36, tm_wday=4, tm_yday=356, tm_isdst=0)
time.struct_time(tm_year=2017, tm_mon=12, tm_mday=22, tm_hour=11, tm_min=42, tm_sec=36, tm_wday=4, tm_yday=356, tm_isdst=0)

3、Python time asctime()方法

Python time asctime() 函數接受時間元組並返回一個可讀的形式為"Tue Dec 11 18:07:14 2008"(2008年12月11日 周二18時07分14秒)的24個字符的字符串

asctime()方法語法:

time.asctime([t])  #t -- 9個元素的元組或者通過函數 gmtime() 或 localtime() 返回的時間值

舉例:

#!/usr/bin/python
import time

t = time.localtime()
print "time.asctime(t): %s " % time.asctime(t)

輸出:

time.asctime(t): Fri Dec 22 11:28:47 2017 

4、Python time ctime()方法

Python time ctime() 函數把一個時間戳(按秒計算的浮點數)轉化為time.asctime()的形式。 如果參數未給或者為None的時候,將會默認time.time()為參數。它的作用相當於 asctime(localtime(secs))。該函數沒有任何返回值。

ctime()方法語法:

time.ctime([ sec ])   #sec -- 要轉換為字符串時間的秒數。

舉例:

#!/usr/bin/python
import time
t = time.localtime()
print  time.asctime(t)
print  time.ctime()

輸出:

Fri Dec 22 14:19:36 2017
Fri Dec 22 14:19:36 2017

5、Python time strftime()方法

Python time strftime() 函數接收以時間元組,並返回以可讀字符串表示的當地時間,格式由參數format決定。

strftime()方法語法:

time.strftime(format[, t])

參數說明:

  • format -- 格式字符串。
  • t -- 可選的參數t是一個struct_time對象

python中時間日期格式化符號:

  • %y 兩位數的年份表示(00-99)
  • %Y 四位數的年份表示(000-9999)
  • %m 月份(01-12)
  • %d 月內中的一天(0-31)
  • %H 24小時制小時數(0-23)
  • %I 12小時制小時數(01-12)
  • %M 分鍾數(00=59)
  • %S 秒(00-59)
  • %a 本地簡化星期名稱
  • %A 本地完整星期名稱
  • %b 本地簡化的月份名稱
  • %B 本地完整的月份名稱
  • %c 本地相應的日期表示和時間表示
  • %j 年內的一天(001-366)
  • %p 本地A.M.或P.M.的等價符
  • %U 一年中的星期數(00-53)星期天為星期的開始
  • %w 星期(0-6),星期天為星期的開始
  • %W 一年中的星期數(00-53)星期一為星期的開始
  • %x 本地相應的日期表示
  • %X 本地相應的時間表示
  • %Z 當前時區的名稱
  • %% %號本身

舉例:

#!/usr/bin/python
import time
print time.localtime();
print time.strftime("%Y-%m-%d %H:%M:%S",time.localtime());
print time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())

輸出:

time.struct_time(tm_year=2017, tm_mon=12, tm_mday=22, tm_hour=14, tm_min=3, tm_sec=2, tm_wday=4, tm_yday=356, tm_isdst=0)
2017-12-22 14:03:02
Fri Dec 22 14:03:02 2017

6、Python time sleep()方法

Python time sleep() 函數推遲調用線程的運行,可通過參數secs指秒數,表示進程掛起的時間

sleep()方法語法:

time.sleep(t)  #t -- 推遲執行的秒數。

舉例:

#!/usr/bin/python
import time
print "Start : %s" % time.ctime()
time.sleep(5)
print "End : %s" % time.ctime()

輸出:

Start : Fri Dec 22 14:21:54 2017
End : Fri Dec 22 14:21:59 2017

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM