一.OS模塊
一).OS模塊的概念:
Python os模塊是Python提供的訪問操作系統(tǒng)功能的模塊,如打開、讀、寫、關(guān)閉文件,訪問目錄等等。使用os模塊Python開發(fā)者可以方便的開發(fā)出跨平臺(tái)的軟件。
使用os模塊可以做到:
- 1、方便的調(diào)用操作系統(tǒng)的基本功能
- 2、開發(fā)跨平臺(tái)的軟件
- 3、os模塊是操作系統(tǒng)相關(guān)功能的輕量級(jí)封裝,對(duì)于特定的復(fù)雜功能還是應(yīng)該使用專用的模塊。如:只想讀取或?qū)懭胛募?,可以使用os.open(),如果要操作路徑, 可以使用os.path模塊;但,如果要在命令行上,讀取所有文件中的所有行,請(qǐng)使用fileinput 模塊;創(chuàng)建臨時(shí)文件和目錄的信息,可以使用tempfile 模塊,高級(jí)文件和目錄處理可以使用shutil 模塊。
二. OS基本操作
1.獲取當(dāng)前 的目錄
- os.curdir 打印出來 . 相對(duì)路徑
import os
os.curdir
'.'
2.獲取當(dāng)前工作目錄
- os.getcwd() 絕對(duì)路徑
import os
os.getcwd()
'/home/jiang/PycharmProjects/111'
3.獲取當(dāng)前目錄下的所有的文件名
fileNames=os.listdir()
fileNames=os.listdir(r'd:\codes')
import os
os.listdir()
['回調(diào)函數(shù)3.py', 'nonloca_text.py', '回調(diào)函數(shù)2.py', '回調(diào)函數(shù).py', '.idea', '222.txt']
os.listdir('/home/jiang/PycharmProjects/111')
['回調(diào)函數(shù)3.py', 'nonloca_text.py', '回調(diào)函數(shù)2.py', '回調(diào)函數(shù).py', '.idea', '222.txt']
4.創(chuàng)建目錄
os.mkdir(r'd:\xxx') #在絕對(duì)路徑下創(chuàng)建目錄,如果已經(jīng)存在,會(huì)把異常
import os
os.mkdir('/home/jiang/PycharmProjects/111/os_test.py')
os.mkdir('os_test01.py')
5.修改目錄
os.rename('修改前','修改后')
os.rename('os_test.py','os_test02.py')
os.listdir()
['os_test02.py', '回調(diào)函數(shù)3.py', 'nonloca_text.py', 'os_test01.py', '回調(diào)函數(shù)2.py', '回調(diào)函數(shù).py', '.idea', '222.txt']
6.刪除目錄和文件
刪除目錄 os.rmdir()
刪除文件 os.remove()
# 刪除目錄 os.rmdir()
os.rmdir('os_test01.py')
os.listdir()
['os_test02.py', '回調(diào)函數(shù)3.py', 'nonloca_text.py', '回調(diào)函數(shù)2.py', '回調(diào)函數(shù).py', '.idea', '222.txt']
# 刪除文件 os.remove()
os.listdir()
['回調(diào)函數(shù)3.py', 'nonloca_text.py', 'os_test.py', '回調(diào)函數(shù)2.py', '回調(diào)函數(shù).py', '.idea', '222.txt']
os.remove('os_test.py')
os.listdir()
['回調(diào)函數(shù)3.py', 'nonloca_text.py', '回調(diào)函數(shù)2.py', '回調(diào)函數(shù).py', '.idea', '222.txt']
7.獲取文件的屬性
os.stat('xxx.txt') #返回各種文件的狀態(tài)信息
- st_size: 普通文件以字節(jié)為單位的大?。话却承┨厥馕募臄?shù)據(jù)。
- st_atime: 上次訪問的時(shí)間。
- st_mtime: 最后一次修改的時(shí)間。
- st_ctime: 由操作系統(tǒng)報(bào)告的"ctime",一般為創(chuàng)建時(shí)間
os.stat('os_test.txt')
os.stat_result(st_mode=33204, st_ino=944347, st_dev=2049, st_nlink=1, st_uid=1000, st_gid=1000, st_size=0, st_atime=1534328554, st_mtime=1534328554, st_ctime=1534328554)
8.路徑的拼接與分割
在當(dāng)前目錄下獲取文件的絕對(duì)路徑
os.path.abspath('xxx.txt')拼接路徑
absPaht = os.path.join(os.getcwd(), 'hahaha.txt')分割路徑
os.path.split(absPath)
# 在當(dāng)前目錄下獲取文件的絕對(duì)路徑
os.path.abspath('os_test.txt')
'/home/jiang/PycharmProjects/111/os_test.txt'
# 拼接路徑
abspath = os.path.join(os.getcwd(),'os_test.py')
abspath
'/home/jiang/PycharmProjects/111/os_test.py'
# 分割路徑
os.path.split(abspath)
('/home/jiang/PycharmProjects/111', 'os_test.py')
9.判斷是否是文件、目錄以及是否存在
- 判斷是否是目錄
os.path.isdir(path) - 判斷是否是文件
os.path.isFile(path) - 判斷是否存在
os.path.exists(path)
import os
os.listdir()
['os_test', '回調(diào)函數(shù)3.py', 'nonloca_text.py', 'os_test.py', '回調(diào)函數(shù)2.py', 'os_test.txt', '回調(diào)函數(shù).py', '.idea', '222.txt']
# 判斷是否是目錄
os.path.isdir('nonloca_text.py')
False
os.path.isdir('os_test')
True
# 判斷是否是文件
os.path.isfile('os_test.py')
True
# 判斷是否存在
os.path.exists('回調(diào)函數(shù)3.py')
True
os.path.exists('os_test')
True
- 獲取文件的路徑的目錄
os.path.dirname(path1) # 返回文件的目錄
os.path.basename(path1) # 返回文件名
os.listdir()
['os_test', '回調(diào)函數(shù)3.py', 'nonloca_text.py', 'os_test.py', '回調(diào)函數(shù)2.py', 'os_test.txt', '回調(diào)函數(shù).py', '.idea', '222.txt']
# 獲取文件的路徑的目錄
os.path.dirname('os_test.py')
''
os.path.basename('os_test.py')
'os_test.py'
11.拓展
os.path.getsize(path) 返回path的大小
os.path.getatime() 返回目錄最后存取時(shí)間
os.path.getmtime() 返回最后修改時(shí)間
os.getpid() 獲取當(dāng)前進(jìn)程id
os.getppid() 獲取當(dāng)前進(jìn)程id的上一級(jí)進(jìn)程id
os.path.getsize('nonloca_text.py')
374
os.path.getatime('nonloca_text.py')
1534251977.7073188
os.path.getmtime('nonloca_text.py')
1534251977.1993375
os.getpid()
8470
os.getppid()
3350
二. datatime 模塊
一). 基本介紹
datetime模塊用于是date和time模塊的合集,datetime有兩個(gè)常量,MAXYEAR和MINYEAR,分別是9999和1.
datetime模塊定義了5個(gè)類,分別是:
- datetime.date:表示日期的類
- datetime.datetime:表示日期時(shí)間的類
- datetime.time:表示時(shí)間的類
- datetime.timedelta:表示時(shí)間間隔,即兩個(gè)時(shí)間點(diǎn)的間隔
-
datetime.tzinfo:時(shí)區(qū)的相關(guān)信息 #不常用
datetime.png
(/home/jiang/圖片/datetime.png)
二).具體用法
1. date類
datetime.date(year, month, day)
- 靜態(tài)方法和字段
- date.max、date.min:date對(duì)象所能表示的最大、最小日期;
- date.resolution:date對(duì)象表示日期的最小單位。這里是天。
- date.today():返回一個(gè)表示當(dāng)前本地日期的date對(duì)象;
- date.fromtimestamp(timestamp):根據(jù)給定的時(shí)間戮,返回一個(gè)date對(duì)象;
from datetime import *
import time
data_max = date.max
print('date.max:',data_max)
data_min = date.min
print('date.min:',data_min)
data_today = date.today()
print('data_today:',data_today)
data_resolution = date.resolution
print('data_resolution:',data_resolution)
data_fromtimestamp = date.fromtimestamp(time.time())
print('data_fromtimestamp:',data_fromtimestamp)
=====================
date.max: 9999-12-31
date.min: 0001-01-01
data_today: 2018-08-15
data_resolution: 1 day, 0:00:00
data_fromtimestamp: 2018-08-15
- 方法和屬性
d1 = date(2018,8,15)#date對(duì)象
d1.year、date.month、date.day:年、月、日;
d1.replace(year, month, day):生成一個(gè)新的日期對(duì)象,用參數(shù)指定的年,月,日代替原有對(duì)象中的屬性。(原有對(duì)象仍保持不變)
d1.timetuple():返回日期對(duì)應(yīng)的time.struct_time對(duì)象;
d1.weekday():返回weekday,如果是星期一,返回0;如果是星期2,返回1,以此類推;
d1.isoweekday():返回weekday,如果是星期一,返回1;如果是星期2,返回2,以此類推;
d1.isocalendar():返回格式如(year,month,day)的元組;
d1.isoformat():返回格式如'YYYY-MM-DD’的字符串;
d1.strftime(fmt):和time模塊format相同。
from datetime import *
import time
now = date(2018,8,15)
print('年:',now.year,'月:',now.month,'日:',now.day)
tomorrow = now.replace(day=16)
print('now.timetuple():',now.timetuple())
print('星期幾:',now.weekday()) # 返回weekday,如果是星期一,返回0;如果是星期2,返回1,以此類推;
print('星期幾:',now.isoweekday()) # 返回weekday,如果是星期一,返回1;如果是星期2,返回2,以此類推;
print('now.isocalendar()',now.isocalendar())
print('now.isoformat()',now.isoformat())
print('now.strftime(fmt)',now.strftime('%Y-%m-%d'))
=================
年: 2018 月: 8 日: 15
now.timetuple(): time.struct_time(tm_year=2018, tm_mon=8, tm_mday=15, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=227, tm_isdst=-1)
星期幾: 2
星期幾: 3
now.isocalendar() (2018, 33, 3)
now.isoformat() 2018-08-15
now.strftime(fmt) 2018-08-15
2. datetime類
datetime相當(dāng)于date和time結(jié)合起來。
datetime.datetime (year, month, day[ , hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] ] )
- 靜態(tài)方法和字段
- datetime.today():返回一個(gè)表示當(dāng)前本地時(shí)間的datetime對(duì)象;
- datetime.now([tz]):返回一個(gè)表示當(dāng)前本地時(shí)間的datetime對(duì)象,如果提供了參數(shù)tz,則獲取tz參數(shù)所指時(shí)區(qū)的本地時(shí)間;
- datetime.utcnow():返回一個(gè)當(dāng)前utc時(shí)間的datetime對(duì)象;#格林威治時(shí)間
- datetime.fromtimestamp(timestamp[, tz]):根據(jù)時(shí)間戮創(chuàng)建一個(gè)datetime對(duì)象,參數(shù)tz指定時(shí)區(qū)信息;
- datetime.utcfromtimestamp(timestamp):根據(jù)時(shí)間戮創(chuàng)建一個(gè)datetime對(duì)象;
- datetime.combine(date, time):根據(jù)date和time,創(chuàng)建一個(gè)datetime對(duì)象;
- datetime.strptime(date_string, format):將格式字符串轉(zhuǎn)換為datetime對(duì)象;
from datetime import *
import time
print('datetime.today():',datetime.today())
print('datetime.now():',datetime.now())
print('datetime.utcnow():',datetime.utcnow())
print('datetime.fromtimestamp():',datetime.fromtimestamp(time.time()))
print('datetime.utcfromtimestamp():',datetime.utcfromtimestamp(time.time()))
=================
datetime.today(): 2018-08-15 20:07:50.806633
datetime.now(): 2018-08-15 20:07:50.806746
datetime.utcnow(): 2018-08-15 12:07:50.806777
datetime.fromtimestamp(): 2018-08-15 20:07:50.806790
datetime.utcfromtimestamp(): 2018-08-15 12:07:50.806801
- 方法和屬性
dt=datetime.now()#datetime對(duì)象
dt.year、month、day、hour、minute、second、microsecond、tzinfo:
dt.date():獲取date對(duì)象;
dt.time():獲取time對(duì)象;
dt. replace ([year, month, day, hour, minute, second, microsecond):
dt. timetuple ()
dt. utctimetuple ()
dt. toordinal ()
dt. weekday ()
dt. isocalendar ()
dt. isoformat ([ sep] )
dt. ctime ():返回一個(gè)日期時(shí)間的C格式字符串,等效于time.ctime(time.mktime(dt.timetuple()));
dt. strftime (format)
from datetime import *
import time
dt = datetime.now()
print('年-月-日-時(shí):分:秒:毫秒:',dt.year,dt.month,dt.day,dt.hour,dt.minute,dt.second,dt.microsecond)
print(tzinfo)
print('dt.date():',dt.date())
print('dt.time():',dt.time())
print('dt.timetuple():',dt.timetuple())
print('dt.utctimetuple():',dt.utctimetuple())
print('dt.toordinal():',dt.toordinal())
print('dt.weekday():',dt.weekday())
print('dt.isocalendar():',dt.isocalendar())
print('dt.isoformat():',dt.isoformat())
print('dt.ctime():',dt.ctime())
print('dt.strftime():',dt.strftime(str(time.time())))
print('dt.replace():',dt.replace(2018,8,16,21,24,45,56))
======================
年-月-日-時(shí):分:秒:毫秒: 2018 8 15 20 26 49 211926
<class 'datetime.tzinfo'>
dt.date(): 2018-08-15
dt.time(): 20:26:49.211926
dt.timetuple(): time.struct_time(tm_year=2018, tm_mon=8, tm_mday=15, tm_hour=20, tm_min=26, tm_sec=49, tm_wday=2, tm_yday=227, tm_isdst=-1)
dt.utctimetuple(): time.struct_time(tm_year=2018, tm_mon=8, tm_mday=15, tm_hour=20, tm_min=26, tm_sec=49, tm_wday=2, tm_yday=227, tm_isdst=0)
dt.toordinal(): 736921
dt.weekday(): 2
dt.isocalendar(): (2018, 33, 3)
dt.isoformat(): 2018-08-15T20:26:49.211926
dt.ctime(): Wed Aug 15 20:26:49 2018
dt.strftime(): 1534336009.2120526
dt.replace(): 2018-08-16 21:24:45.000056
3. time類
datetime.time(hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] )
time.min、time.max:time類所能表示的最小、最大時(shí)間。其中,time.min = time(0, 0, 0, 0), time.max = time(23, 59, 59, 999999);
time.resolution:時(shí)間的最小單位,這里是1微秒;
- 方法和屬性
t1 = time(10,23,15)#time對(duì)象
t1.hour、t1.minute、t1.second、t1.microsecond:時(shí)、分、秒、微秒;
t1.tzinfo:時(shí)區(qū)信息;
t1.replace([ hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] ] ):創(chuàng)建一個(gè)新的時(shí)間對(duì)象,用參數(shù)指定的時(shí)、分、秒、微秒代替原有對(duì)象中的屬性(原有對(duì)象仍保持不變);
t1.isoformat():返回型如"HH:MM:SS"格式的字符串表示;
t1.strftime(fmt):同time模塊中的format;
from datetime import *
tm = time(21,6,56,10)
print('時(shí):分:秒:毫秒:',tm.hour,tm.minute,tm.second,tm.microsecond)
print('tm.tzinfo:',tm.tzinfo)
print('tm.replace:',tm.replace(22,13,25,96))
print('tm.isoformat:',tm.isoformat())
print('tm.strftime:',tm.strftime("%X"))
========================
時(shí):分:秒:毫秒: 21 6 56 10
tm.tzinfo: None
tm.replace: 22:13:25.000096
tm.isoformat: 21:06:56.000010
tm.strftime: 21:06:56
4. timedelta類,時(shí)間加減
使用timedelta可以很方便的在日期上做天days,小時(shí)hour,分鐘,秒,毫秒,微妙的時(shí)間計(jì)算,如果要計(jì)算月份則需要另外的辦法。
from datetime import *
dt = datetime.now()
# 日期減一天
dt1 = dt + timedelta(days=-1) #昨天
dt2 = dt - timedelta(days=1) #昨天
dt3 = dt + timedelta(days=1) #明天
delta_obj = dt3-dt
print(type(delta_obj),delta_obj)
print(delta_obj.days,delta_obj.total_seconds())
================
<class 'datetime.timedelta'> 1 day, 0:00:00
1 86400.0
5. tzinfo時(shí)區(qū)類
from datetime import datetime, tzinfo,timedelta
"""
tzinfo是關(guān)于時(shí)區(qū)信息的類
tzinfo是一個(gè)抽象類,所以不能直接被實(shí)例化
"""
class UTC(tzinfo):
"""UTC"""
def __init__(self,offset = 0):
self._offset = offset
def utcoffset(self, dt):
return timedelta(hours=self._offset)
def tzname(self, dt):
return "UTC +%s" % self._offset
def dst(self, dt):
return timedelta(hours=self._offset)
#北京時(shí)間
beijing = datetime(2011,11,11,0,0,0,tzinfo = UTC(8))
print ("beijing time:",beijing)
#曼谷時(shí)間
bangkok = datetime(2011,11,11,0,0,0,tzinfo = UTC(7))
print ("bangkok time",bangkok)
#北京時(shí)間轉(zhuǎn)成曼谷時(shí)間
print ("beijing-time to bangkok-time:",beijing.astimezone(UTC(7)))
#計(jì)算時(shí)間差時(shí)也會(huì)考慮時(shí)區(qū)的問題
timespan = beijing - bangkok
print ("時(shí)差:",timespan)
=============================
beijing time: 2011-11-11 00:00:00+08:00
bangkok time 2011-11-11 00:00:00+07:00
beijing-time to bangkok-time: 2011-11-10 23:00:00+07:00
時(shí)差: -1 day, 23:00:00
time 模塊
ime模塊中時(shí)間表現(xiàn)的格式主要有三種:
a、timestamp時(shí)間戳,時(shí)間戳表示的是從1970年1月1日00:00:00開始按秒計(jì)算的偏移量
b、struct_time時(shí)間元組,共有九個(gè)元素組。
c、format time 格式化時(shí)間,已格式化的結(jié)構(gòu)使時(shí)間更具可讀性。包括自定義格式和固定格式。

1. 時(shí)間格式轉(zhuǎn)換圖

2. 主要time生成方法和time格式轉(zhuǎn)換方法實(shí)例
- 基本概念
時(shí)間戳:以整型或者浮點(diǎn)型來表示一個(gè)時(shí)間間隔,以1970年1月1日0點(diǎn)0分0秒為參考時(shí)間;
時(shí)間元組: 一種python的數(shù)據(jù)結(jié)構(gòu),有九個(gè)整型內(nèi)容
字符串形式:2017/10/19, 2017-10-19, 10:15:54, 20171018獲取當(dāng)前時(shí)間戳
time.time()獲取當(dāng)?shù)貢r(shí)間
time.localtime()把時(shí)間戳轉(zhuǎn)成時(shí)間元組 gmtime
time.gmtime(time.time())-
把時(shí)間元組轉(zhuǎn)成時(shí)間戳
time.mktime(timeTuple)
-
把時(shí)間元組轉(zhuǎn)成字符串
time.strftime()
time.strftime('%Y-%M-%d %H:%M:%S',timeTuple) -->把時(shí)間元組轉(zhuǎn)成這種格式的字符串 -
把時(shí)間字符串轉(zhuǎn)成時(shí)間元組
time.strptime()st = '2018-10-12'
st2 = '2018/10/13't_1 = time.strptime(st, '%Y-%m-%d') -->前面參數(shù)是字符串,后面參數(shù)是字符串的格式
t_2 = time.strptime(st2, '%Y/%m/%d') 把時(shí)間戳轉(zhuǎn)成字符串
time.ctime()
import time
# 獲取當(dāng)前時(shí)間戳(timestamp)
t = time.time()
print('獲取當(dāng)前時(shí)間戳:',t)
# 獲取當(dāng)?shù)貢r(shí)間(struct_time
s_t = time.localtime(time.time())
print('獲取當(dāng)?shù)貢r(shí)間:',s_t)
# 把時(shí)間戳轉(zhuǎn)成時(shí)間元組 gmtime
t_g = time.gmtime(time.time())
print('把時(shí)間戳轉(zhuǎn)成時(shí)間元組:',t_g)
# 把時(shí)間元組轉(zhuǎn)成時(shí)間戳 mktime(timeTuple)
t_m = time.mktime(t_g)
print('把時(shí)間戳轉(zhuǎn)成時(shí)間元組:',t_m)
# 把時(shí)間元組轉(zhuǎn)成字符串 time.strftime()
t_s = time.strftime("%Y-%m-%d %X",time.localtime())
print('把時(shí)間元組轉(zhuǎn)成字符串:',t_s)
# 生成固定格式的時(shí)間表示格式
t_a = time.asctime(time.localtime())
print('生成固定格式的時(shí)間表示格式',t_a)
# 把時(shí)間戳轉(zhuǎn)成字符串 time(time.time())
t_c = time.ctime(time.time())
print('把時(shí)間戳轉(zhuǎn)成字符串',t_c)
====================
獲取當(dāng)前時(shí)間戳: 1534421104.0705442
獲取當(dāng)?shù)貢r(shí)間: time.struct_time(tm_year=2018, tm_mon=8, tm_mday=16, tm_hour=20, tm_min=5, tm_sec=4, tm_wday=3, tm_yday=228, tm_isdst=0)
把時(shí)間戳轉(zhuǎn)成時(shí)間元組: time.struct_time(tm_year=2018, tm_mon=8, tm_mday=16, tm_hour=12, tm_min=5, tm_sec=4, tm_wday=3, tm_yday=228, tm_isdst=0)
把時(shí)間戳轉(zhuǎn)成時(shí)間元組: 1534392304.0
把時(shí)間元組轉(zhuǎn)成字符串: 2018-08-16 20:05:04
生成固定格式的時(shí)間表示格式 Thu Aug 16 20:05:04 2018
把時(shí)間戳轉(zhuǎn)成字符串 Thu Aug 16 20:05:04 2018
3. struct_time元組元素結(jié)構(gòu)
| 屬性 | 值 |
|---|---|
| tm_year(年) | 比如2018 |
| tm_mon(月) | 1 - 12 |
| tm_mday(日) | 1 - 31 |
| tm_hour(時(shí)) | 0 - 23 |
| tm_min(分) | 0 - 59 |
| tm_sec(秒) | 0 - 61 |
| tm_wday(weekday) | 0 - 6(0表示周日) |
| tm_yday(一年中的第幾天) | 1 - 366 |
| tm_isdst(是否是夏令時(shí)) | 默認(rèn)為-1 |
4. format time結(jié)構(gòu)化表示
| 格式 | 含義 |
|---|---|
| %a | 本地(locale)簡(jiǎn)化星期名稱 |
| %A | 本地完整星期名稱 |
| %b | 本地簡(jiǎn)化月份名稱 |
| %B | 本地完整月份名稱 |
| %c | 本地相應(yīng)的日期和時(shí)間表示 |
| %d | 一個(gè)月中的第幾天(01 - 31) |
| %H | 一天中的第幾個(gè)小時(shí)(24小時(shí)制,00 - 23) |
| %I | 第幾個(gè)小時(shí)(12小時(shí)制,01 - 12) |
| %j | 一年中的第幾天(001 - 366) |
| %m | 月份(01 - 12 |
| %M | 分鐘數(shù)(00 - 59) |
| %p | 本地am或者pm的相應(yīng)符 |
| %S | 秒(01 - 61 |
| %U | 一年中的星期數(shù)。(00 - 53星期天是一個(gè)星期的開始。)第一個(gè)星期天之前的所有天數(shù)都放在第0周。 |
| %w | 和%U基本相同,不同的是%W以星期一為一個(gè)星期的開始。 |
| %x | 本地相應(yīng)日期 |
| %X | 本地相應(yīng)時(shí)間 |
| %y | 去掉世紀(jì)的年份(00 - 99) |
| %Y | 完整的年份 |
| %Z | 時(shí)區(qū)的名字(如果不存在為空字符) |
| %% | ‘%’字符 |
5. time加減
import time
t1 = time.time()
t2=t1+10
===============
time.ctime(): 1534422377.9069533
time.ctime(): 1534422387.9069533
