python—time模組使用詳解
python中的time模組提供一些方法用來進行關於時間的操作,time模組中有以下方法可供使用:
time() — 返回當前時間的時間戳。
呼叫:time.time(), 可用於計算程式執行的時間,測試演算法的優劣性。
sleep() — 使程式暫停數秒。
呼叫:time.sleep(seconds), 傳入秒數, 程式執行到這個函式時暫停一段時間。
gmtime() — 以time.struct_time的格式返回當前UTC時間。
呼叫:time.gmtime([seconds]),傳入時間戳,得到UTC tuple,如果未傳入引數,以當前時間代替。
例如:
>>> time.gmtime(time.time())
time.struct_time(tm_year=2017, tm_mon=8, tm_mday=16, tm_hour=6, tm_min=39, tm_sec=46, tm_wday=2, tm_yday=228, tm_isdst=0)
localtime() — 以time.struct_time的格式返回當前時間(本地時區)。
用法等同於gmtime().
asctime() — 返回關於時間的格式化字串, 例如`Sat Jun 06 16:26:11 1998`
呼叫:time.asctime([tuple]),tuple形式即time.struct_time。
例如:
>>> time.asctime(time.localtime()) `Wed Aug 16 14:59:26 2017`
ctime() — 返回同asctime()一樣的字串。
呼叫:time.ctime(seconds),傳入時間戳。
例如:
>>> time.ctime(time.time()) `Wed Aug 16 15:02:03 2017`
mktime() — 返回時間戳。
呼叫:time.mktime(tuple),tuple形式即time.struct_time。
例如:
>>> time.mktime(time.localtime())
1502867286.0
strftime() — 將time.struct_time轉成可格式化字串。
呼叫:time.strftime(format[, tuple])
例如:
>>> time.strftime("%Y/%m/%d %H:%M:%S", time.localtime()) `2017/08/16 15:15:56`
常用格式程式碼:
%Y 以十進位制數字表示年
%m 以十進位制數字表示月
%d 以十進位制數字表示天
%H 以十進位制數字表示時
%M 以十進位制數字表示分
%S 以十進位制數字表示秒
%z 表示時區偏離UTC的時間差
例如(東八區比UTC快0天8時0分0秒):
>>> time.strftime("%z", time.localtime()) `+0800`
%a 星期的縮寫
%A 星期的全寫
%b 月份的縮寫
%B 月份的大寫
%c 等同於ctime()返回的格式
%I 以12小時製表示時
%p 表示上午還是下午
例如:
>>> time.strftime("%a %b %I:%M:%S%p", time.localtime()) `Wed Aug 03:38:33PM` >>> time.strftime("%A %B %I:%M:%S%p", time.localtime()) `Wednesday August 03:39:07PM` >>> time.strftime("%c", time.localtime()) `Wed Aug 16 15:39:19 2017`
strptime() — 將格式化字串轉成tuple(time.struct_time)
呼叫:time.strptime(string, format)
例如(格式程式碼同上):
>>> time.strptime("2017/08/16 15:15:56", "%Y/%m/%d %H:%M:%S") time.struct_time(tm_year=2017, tm_mon=8, tm_mday=16, tm_hour=15, tm_min=15, tm_sec=56, tm_wday=2, tm_yday=228, tm_isdst=-1)
相關文章
- Python之time模組詳解Python
- python—random模組使用詳解Pythonrandom
- python—hashlib模組使用詳解Python
- Python之Requests模組使用詳解Python
- Python模組:time模組Python
- python模組詳解Python
- Python3 pickle模組的使用詳解Python
- Python的畫圖模組turtle使用詳解Python
- python:time模組Python
- Python os模組詳解Python
- python docopt模組詳解Python
- python 詳解re模組Python
- Node.js 核心模組 Timers 詳解Node.js
- NSTimer使用詳解
- python:timeit模組Python
- python之time模組Python
- Python之OS模組詳解Python
- python requests模組詳解薦Python
- Python包(模組)管理詳解Python
- 【python】詳解time模組功能asctime、localtime、mktime、sleep、strptime、strftime、time等函式以及時間的加減運算Python函式
- python時間模組time和datetimePython
- Python入門—time模組Python
- Python time模組學習Python
- iOS 中 NSTimer 使用詳解iOS
- Python基礎12(模組與datetime模組)Python
- Python模組學習:datetimePython
- Python 正規表示式模組詳解Python
- python IO模組【二】:open函式詳解Python函式
- python3.x中argparse模組詳解Python
- Python隨機數生成模組random詳解Python隨機random
- Python3 queue佇列模組詳解Python佇列
- Python學習之 datetime模組Python
- 每週一個 Python 模組 | timePython
- Python time模組詳解(時間戳↔元組形式↔格式化形式三者轉化)Python時間戳
- Python學習【第十二篇】time & datetime模組Python
- Python的常見模組:OS和 time模組介紹Python
- Python集合使用詳解Python
- iOS Runtime詳解iOS