常用模块之 time,datetime,random,os,sys
time與datetime模塊
先認(rèn)識(shí)幾個(gè)python中關(guān)于時(shí)間的名詞:
時(shí)間戳(timestamp):通常來說,時(shí)間戳表示的是從1970年1月1日00:00:00開始按秒計(jì)算的偏移量。我們運(yùn)行“type(time.time())”,返回的是float類型。1970年之前的日期無法以此表示,太遙遠(yuǎn)的日期也不行,UNIX和Windows只支持到2038年,時(shí)間戳最適合做日期運(yùn)算。
格式化的時(shí)間字符串(Format String):按照指定格式輸出日期字符串
結(jié)構(gòu)化的時(shí)間(struct_time):struct_time元組共有9個(gè)元素共九個(gè)元素:(年,月,日,時(shí),分,秒,一年中第幾周,一年中第幾天,夏令時(shí))
import time#我們先以當(dāng)前時(shí)間為準(zhǔn),讓大家快速認(rèn)識(shí)三種形式的時(shí)間print(time.time()) # 時(shí)間戳:1487130156.419527 print(time.strftime("%Y-%m-%d %X")) #格式化的時(shí)間字符串:'2017-02-15 11:40:53'print(time.localtime()) #本地時(shí)區(qū)的struct_time print(time.gmtime()) #UTC時(shí)區(qū)的struct_time 三種形式的時(shí)間實(shí)例 """python中時(shí)間日期格式化符號(hào):------------------------------------%y 兩位數(shù)的年份表示(00-99)%Y 四位數(shù)的年份表示(000-9999)%m 月份(01-12)%d 月內(nèi)中的一天(0-31)%H 24小時(shí)制小時(shí)數(shù)(0-23)%I 12小時(shí)制小時(shí)數(shù)(01-12)%M 分鐘數(shù)(00=59)%S 秒(00-59)%a 本地簡化星期名稱%A 本地完整星期名稱%b 本地簡化的月份名稱%B 本地完整的月份名稱%c 本地相應(yīng)的日期表示和時(shí)間表示%j 年內(nèi)的一天(001-366)%p 本地A.M.或P.M.的等價(jià)符%U 一年中的星期數(shù)(00-53)星期天為星期的開始%w 星期(0-6),星期天為星期的開始%W 一年中的星期數(shù)(00-53)星期一為星期的開始%x 本地相應(yīng)的日期表示%X 本地相應(yīng)的時(shí)間表示%Z 當(dāng)前時(shí)區(qū)的名稱 # 亂碼%% %號(hào)本身 """ 常用的時(shí)間日期格式化符號(hào)由于計(jì)算機(jī)只能讀懂時(shí)間戳,所以在一些特定的場景下我們會(huì)把上面三種時(shí)間的表示方式進(jìn)行轉(zhuǎn)換
# localtime([secs]) # 將一個(gè)時(shí)間戳轉(zhuǎn)換為當(dāng)前時(shí)區(qū)的struct_time。secs參數(shù)未提供,則以當(dāng)前時(shí)間為準(zhǔn)。 time.localtime()time.localtime(1539582935.9421027)gmtime([secs]) 和localtime()方法類似,gmtime()方法是將一個(gè)時(shí)間戳轉(zhuǎn)換為UTC時(shí)區(qū)(0時(shí)區(qū))的struct_time。# mktime(t) : 將一個(gè)struct_time轉(zhuǎn)化為時(shí)間戳。print(time.mktime(time.localtime()))# strftime(format[, t]) : 把一個(gè)代表時(shí)間的元組或者struct_time(如由time.localtime()和# time.gmtime()返回)轉(zhuǎn)化為格式化的時(shí)間字符串。如果t未指定,將傳入time.localtime()。如果元組中任何一個(gè)# 元素越界,ValueError的錯(cuò)誤將會(huì)被拋出。print(time.strftime("%Y-%m-%d %X", time.localtime()))#2018-10-15 13:57:56# time.strptime(string[, format])# 把一個(gè)格式化時(shí)間字符串轉(zhuǎn)化為struct_time。實(shí)際上它和strftime()是逆操作。print(time.strptime('2011-05-05 16:37:06', '%Y-%m-%d %X'))#time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=16, tm_min=37, tm_sec=6,# tm_wday=3, tm_yday=125, tm_isdst=-1)#在這個(gè)函數(shù)中,format默認(rèn)為:"%a %b %d %H:%M:%S %Y"。 利用結(jié)構(gòu)化時(shí)間轉(zhuǎn)換 # asctime([t]) : 把一個(gè)表示時(shí)間的元組或者struct_time表示為這種形式:'Sun Jun 20 23:21:05 1993'。 # 如果沒有參數(shù),將會(huì)將time.localtime()作為參數(shù)傳入。 print(time.asctime())#Sun Sep 11 00:43:43 2016# ctime([secs]) : 把一個(gè)時(shí)間戳(按秒計(jì)算的浮點(diǎn)數(shù))轉(zhuǎn)化為time.asctime()的形式。如果參數(shù)未給或者為 # None的時(shí)候,將會(huì)默認(rèn)time.time()為參數(shù)。它的作用相當(dāng)于time.asctime(time.localtime(secs))。 print(time.ctime()) # Sun Sep 11 00:46:38 2016 print(time.ctime(time.time())) # Sun Sep 11 00:46:38 2016 時(shí)間戳與格式化時(shí)間轉(zhuǎn)換為時(shí)間字符串 時(shí)間加減 import datetimeprint(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925 print(datetime.date.fromtimestamp(time.time()) ) # 時(shí)間戳直接轉(zhuǎn)成日期格式 2016-08-19 print(datetime.datetime.now() ) print(datetime.datetime.now() + datetime.timedelta(3)) #當(dāng)前時(shí)間+3天 print(datetime.datetime.now() + datetime.timedelta(-3)) #當(dāng)前時(shí)間-3天 print(datetime.datetime.now() + datetime.timedelta(hours=3)) #當(dāng)前時(shí)間+3小時(shí) print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #當(dāng)前時(shí)間+30分 時(shí)間替換 c_time = datetime.datetime.now() print(c_time.replace(minute=3,hour=2)) 時(shí)間運(yùn)算random模塊
import randomprint(random.random()) #(0,1)----float 大于0且小于1之間的小數(shù)print(random.randint(1,3)) #[1,3] 大于等于1且小于等于3之間的整數(shù)print(random.randrange(1,3)) #[1,3) 大于等于1且小于3之間的整數(shù)print(random.choice([1,'23',[4,5]])) #1或者23或者[4,5]print(random.sample([1,'23',[4,5]],2)) #列表元素任意2個(gè)組合print(random.uniform(1,3)) #大于1小于3的小數(shù),如1.927109612082716 item=[1,3,5,7,9] random.shuffle(item) #打亂item的順序,相當(dāng)于"洗牌" print(item) random常見用法os模塊
os模塊是與計(jì)算機(jī)操作系統(tǒng)交互的一個(gè)接口
os.getcwd() 獲取當(dāng)前工作目錄,即當(dāng)前python腳本工作的目錄路徑 os.chdir("dirname") 改變當(dāng)前腳本工作目錄;相當(dāng)于shell下cd os.curdir 返回當(dāng)前目錄: ('.') os.pardir 獲取當(dāng)前目錄的父目錄字符串名:('..') os.makedirs('dirname1/dirname2') 可生成多層遞歸目錄 os.removedirs('dirname1') 若目錄為空,則刪除,并遞歸到上一級(jí)目錄,如若也為空,則刪除,依此類推 os.mkdir('dirname') 生成單級(jí)目錄;相當(dāng)于shell中mkdir dirname os.rmdir('dirname') 刪除單級(jí)空目錄,若目錄不為空則無法刪除,報(bào)錯(cuò);相當(dāng)于shell中rmdir dirname os.listdir('dirname') 列出指定目錄下的所有文件和子目錄,包括隱藏文件,并以列表方式打印 os.remove() 刪除一個(gè)文件 os.rename("oldname","newname") 重命名文件/目錄 os.stat('path/filename') 獲取文件/目錄信息 os.sep 輸出操作系統(tǒng)特定的路徑分隔符,win下為"\\",Linux下為"/" os.linesep 輸出當(dāng)前平臺(tái)使用的行終止符,win下為"\t\n",Linux下為"\n" os.pathsep 輸出用于分割文件路徑的字符串 win下為;,Linux下為: os.name 輸出字符串指示當(dāng)前使用平臺(tái)。win->'nt'; Linux->'posix' os.system("bash command") 運(yùn)行shell命令,直接顯示 os.environ 獲取系統(tǒng)環(huán)境變量 os.path.abspath(path) 返回path規(guī)范化的絕對(duì)路徑 os.path.split(path) 將path分割成目錄和文件名二元組返回 os.path.dirname(path) 返回path的目錄。其實(shí)就是os.path.split(path)的第一個(gè)元素 os.path.basename(path) 返回path最后的文件名。如何path以/或\結(jié)尾,那么就會(huì)返回空值。即os.path.split(path)的第二個(gè)元素 os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False os.path.isabs(path) 如果path是絕對(duì)路徑,返回True os.path.isfile(path) 如果path是一個(gè)存在的文件,返回True。否則返回False os.path.isdir(path) 如果path是一個(gè)存在的目錄,則返回True。否則返回False os.path.join(path1[, path2[, ...]]) 將多個(gè)路徑組合后返回,第一個(gè)絕對(duì)路徑之前的參數(shù)將被忽略 os.path.getatime(path) 返回path所指向的文件或者目錄的最后存取時(shí)間 os.path.getmtime(path) 返回path所指向的文件或者目錄的最后修改時(shí)間 os.path.getsize(path) 返回path的大小 os操作大全 os.path.normpath()在Linux和Mac平臺(tái)上,該函數(shù)會(huì)原樣返回path,在windows平臺(tái)上會(huì)將路徑中所有字符轉(zhuǎn)換為小寫,并將所有斜杠轉(zhuǎn)換為飯斜杠。 >>> os.path.normcase('c:/windows\\system32\\') 'c:\\windows\\system32\\' 規(guī)范化路徑,如..和/ >>> os.path.normpath('c://windows\\System32\\../Temp/') 'c:\\windows\\Temp' >>> a='/Users/jieli/test1/\\\a1/\\\\aa.py/../..' >>> print(os.path.normpath(a)) /Users/jieli/test1 os.path.normcase()與os.path.normpath() os路徑處理 #方式一:推薦使用 import os #具體應(yīng)用 import os,sys possible_topdir = os.path.normpath(os.path.join(os.path.abspath(__file__),os.pardir, #上一級(jí) os.pardir,os.pardir )) sys.path.insert(0,possible_topdir)#方式二:不推薦使用 os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 路徑處理sys模塊
sys.argv #命令行參數(shù)List,第一個(gè)元素是程序本身路徑 sys.modules.keys() #返回所有已經(jīng)導(dǎo)入的模塊列表 sys.exc_info() #獲取當(dāng)前正在處理的異常類,exc_type、exc_value、exc_traceback當(dāng)前處理的異常詳細(xì)信息 sys.exit(n) #程序,正常退出時(shí)exit(0) sys.hexversion #獲取Python解釋程序的版本值,16進(jìn)制格式如:0x020403F0 sys.version #獲取Python解釋程序的版本信息 sys.maxint #最大的Int值 sys.maxunicode #最大的Unicode值 sys.modules #返回系統(tǒng)導(dǎo)入的模塊字段,key是模塊名,value是模塊 sys.path #返回模塊的搜索路徑,初始化時(shí)使用PYTHONPATH環(huán)境變量的值 sys.platform #返回操作系統(tǒng)平臺(tái)名稱 sys.stdout #標(biāo)準(zhǔn)輸出 sys.stdin #標(biāo)準(zhǔn)輸入 sys.stderr #錯(cuò)誤輸出 sys.exc_clear() #用來清除當(dāng)前線程所出現(xiàn)的當(dāng)前的或最近的錯(cuò)誤信息 sys.exec_prefix #返回平臺(tái)獨(dú)立的python文件安裝的位置 sys.byteorder #本地字節(jié)規(guī)則的指示器,big-endian平臺(tái)的值是'big',little-endian平臺(tái)的值是'little' sys.copyright #記錄python版權(quán)相關(guān)的東西 sys.api_version #解釋器的C的API版本 sys.version_info #獲取Python解釋器的版本信息 sys.getwindowsversion #獲取Windows的版本 sys.getdefaultencoding #返回當(dāng)前你所用的默認(rèn)的字符編碼格式 sys.getfilesystemencoding #返回將Unicode文件名轉(zhuǎn)換成系統(tǒng)文件名的編碼的名字 sys.setdefaultencoding(name) #用來設(shè)置當(dāng)前默認(rèn)的字符編碼 sys.builtin_module_names #Python解釋器導(dǎo)入的模塊列表 sys.executable #Python解釋程序路徑 sys.stdin.readline #從標(biāo)準(zhǔn)輸入讀一行,sys.stdout.write("a") 屏幕輸出a View Code處理模塊:我們?cè)谑褂媚K的某一個(gè)功能前,需要用import,__import__命令導(dǎo)入。那我們?cè)趫?zhí)行import module_name的時(shí)候,python內(nèi)部發(fā)生了什么呢?簡單的說,就是搜索module_name。根據(jù)sys.path的路徑來搜索module.name
import sys print(sys.path)['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client'] View Code我們以后寫好的模塊就可以放到上面的某一個(gè)目錄下,便可以正確搜索到了。當(dāng)然也可以添加自己的模塊路徑。sys.path.append(“my module path”)。
>>> sys.path.append('my module path') >>> sys.path ['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', 'my module path'] View Codepath列表是一個(gè)由目錄名構(gòu)成的列表, Python 從中查找擴(kuò)展模塊( Python 源模塊, 編譯模塊,或者二進(jìn)制擴(kuò)展).
啟動(dòng) Python 時(shí),這個(gè)列表根據(jù)內(nèi)建規(guī)則, PYTHONPATH 環(huán)境變量的內(nèi)容, 以及注冊(cè)表( Windows 系統(tǒng))等進(jìn)行初始化.
由于它只是一個(gè)普通的列表, 你可以在程序中對(duì)它進(jìn)行操作。使用sys模塊查找已導(dǎo)入的模塊(sys.modules):
modules 字典包含所有加載的模塊。 import 語句在從磁盤導(dǎo)入內(nèi)容之前會(huì)先檢查這個(gè)字典。Python 在處理你的腳本之前就已經(jīng)導(dǎo)入了很多模塊.
打印進(jìn)度條
#指定寬度 print("[%-15s]"%'#') print("[%-15s]"%'##')#打印% print("%s%%"%(100)) #第二個(gè)%號(hào)代表取消第一個(gè)%的特殊意義#可傳參來控制寬度 print('[%%-%ds]' %50) #[%-50s] print(('[%%-%ds]' %50) %'#') print(('[%%-%ds]' %50) %'##') print(('[%%-%ds]' %50) %'###')''' 字符串輸出 %s,%10s--右對(duì)齊,占位符10位;%-10-----左對(duì)齊,占位符10位;''' import sys import timedef progress(percent,width=50):if percent >= 1:percent=1show_str=('[%%-%ds]' %width) %(int(width*percent)*'#')print('\r%s %d%%' %(show_str,int(100*percent)),file=sys.stdout,flush=True,end='')#\r是回車的意思#應(yīng)用 data_size=102500 recv_size=0 while recv_size < data_size:time.sleep(0.1) #模擬數(shù)據(jù)的傳輸延遲recv_size+=1024 #每次收1024 percent=recv_size/data_size #接收的比例progress(percent,width=70) #進(jìn)度條的寬度70 View Codeprint官方文檔分析
print(…) print(value, …, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream.參數(shù)解析 value:需要輸出的值,可以是多個(gè),用”,”分隔。 sep:多個(gè)輸出值之間的間隔,默認(rèn)為一個(gè)空格。 end:輸出語句結(jié)束以后附加的字符串,默認(rèn)是換行(’\n’)。 file:輸出的目標(biāo)對(duì)象,可以是文件也可以是數(shù)據(jù)流,默認(rèn)是“sys.stdout”。 flush:flush值為True或者False,默認(rèn)為Flase,表示是否立刻將輸出語句輸出到目標(biāo)對(duì)象。 print參數(shù)分析 默認(rèn):print(value, …, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)>>> print("hello world") hello world12當(dāng)value有多個(gè):>>> print("hello","world") hello world12當(dāng)sep為”,”>>> print("hello","world",sep=",") hello,world12當(dāng)end為“”>>>print("hello","world",end="") >>>print("hello","world") hello worldhello world123當(dāng)file指向test.txttest = open("test.txt", "w") print("hello","world",sep="\n", file=test) 123此時(shí)當(dāng)前目錄下會(huì)新建一個(gè)test.txt文件里面內(nèi)容為hello world12flush=False 該參數(shù)只有兩個(gè)選項(xiàng)True or False。 當(dāng)flush=False時(shí),輸出值會(huì)存在緩存,然后在文件被關(guān)閉時(shí)寫入。 當(dāng)flush=True時(shí),輸出值強(qiáng)制寫入文件。 實(shí)際舉例functools
該模塊為高階函數(shù)提供支持——作用于或返回函數(shù)的函數(shù)被稱為高階函數(shù)。在該模塊看來,一切可調(diào)用的對(duì)象均可視為本模塊中所說的“函數(shù)”。
python3.6中的functools
import functools for i in dir(functools):print(i)運(yùn)行結(jié)果 ''' MappingProxyType RLock WRAPPER_ASSIGNMENTS WRAPPER_UPDATES WeakKeyDictionary _CacheInfo _HashedSeq __all__ __builtins__ __cached__ __doc__ __file__ __loader__ __name__ __package__ __spec__ _c3_merge _c3_mro _compose_mro _convert _find_impl _ge_from_gt _ge_from_le _ge_from_lt _gt_from_ge _gt_from_le _gt_from_lt _le_from_ge _le_from_gt _le_from_lt _lru_cache_wrapper _lt_from_ge _lt_from_gt _lt_from_le _make_key cmp_to_key get_cache_token lru_cache namedtuple partial partialmethod recursive_repr reduce singledispatch total_ordering update_wrapper wraps '''partial函數(shù)(偏函數(shù))
把一個(gè)函數(shù)的某些參數(shù)設(shè)置默認(rèn)值,返回一個(gè)新的函數(shù),調(diào)用這個(gè)新函數(shù)會(huì)更簡單
import functoolsdef show_parameter(*args, **kw):print(args)print(kw)p1 = functools.partial(show_parameter(), 1, 2, 3)p1() ''' (1, 2, 3) {} ''' p1(4, 5, 6) ''' (1, 2, 3, 4, 5, 6) {} ''' p1(a='python', b='itcast') ''' (1, 2, 3) {'a': 'python', 'b': 'itcast'} '''p2 = functools.partial(show_parameter, a=3, b='linux')p2() ''' () {'a': 3, 'b': 'linux'} ''' p2(1, 2) ''' (1, 2) {'a': 3, 'b': 'linux'} ''' p2(a='python', b='itcast') ''' () {'a': 'python', 'b': 'itcast'} '''wraps函數(shù)
使用裝飾器時(shí),有一些細(xì)節(jié)需要被注意。例如,被裝飾后的函數(shù)其實(shí)已經(jīng)是另外一個(gè)函數(shù)了(函數(shù)名等函數(shù)屬性會(huì)發(fā)生改變)。
添加后由于函數(shù)名和函數(shù)的doc發(fā)生了改變,對(duì)測(cè)試結(jié)果有一些影響,例如
def outter(func):"outter function"def wrapper():"wrapper function"print('outter something')return func()return wrapper@outter def test():"test function"print('I am test')test()print(test.__doc__) #這里面的__doc__改變了執(zhí)行結(jié)果 ''' outter something I am test wrapper function '''所以,Python的functools包中提供了一個(gè)叫wraps的裝飾器來消除這樣的副作用
import functoolsdef outter(func):"outter function"@functools.wraps(func)def wrapper():"wrapper function"print('outter something')return func()return wrapper@outter def test():"test function"print('I am test')test() print(test.__doc__)執(zhí)行結(jié)果 ''' outter something I am test test function '''
?
轉(zhuǎn)載于:https://www.cnblogs.com/596014054-yangdongsheng/p/9770662.html
總結(jié)
以上是生活随笔為你收集整理的常用模块之 time,datetime,random,os,sys的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Apache——Introduction
- 下一篇: Ubuntu防火墙:ufw