一、了解模块导入的基本知识

此部分此处不展开细说import导入,仅写几个点目前的认知即可。其它内容待日后有深入理解了再来细说

1、import可以导入的两种不同的内容

1.1 *.py文件结尾的文件

1.2 package文件

package和文件夹图标类似,package中又__init__.py的文件

2、模块导入的几种导入方式

2.1 from xxx import xxx as xxx

2.2 from xxx import xxx as xxx as xxx 别名

2.3 import xxx

3、import 和 from xxx import 的区别

import xxx的本质是执行py文件,import package是执行__init__.py

from xxx import xxx 的本质是将xxx部分的内容复制到本地,进行调用。

4、需要重点掌握给sys(python解释器)添加环境变量的方法

4.1 os.path.abs(文件)

4.2 os.path.dirname(绝对路径)

4.3 sys.path.append()/sys.path.insert()

二、time模块-->时间模块

1、要熟悉时间的三种表示方式

1.1、格式化字符串 ‘2018-2-1 11:11:12’

此处的格式我们可以随意去自定义,其实质是按照固定的格式,从时间的9元组中获取需要的变量,根据定义的格式输出字符串

1.2、时间戳

一串数字,用来表示和1970年的时间间隔,单位为s。

注意点:一个时间戳所换算成的时间九元组是固定的。但是,根据时区的不同,python会进行相应的转换,转换成当地的时间。在熟悉了这个情况后,在后面的时间表示方式的转换中,要明确我要转换成的是标准时间还是当地时间。

1.3、元组 struct_time 9个元素

year (including century, e.g. 1998) 

month (1-12)

day (1-31)

hours (0-23)

minutes (0-59)

seconds (0-59)

weekday (0-6, Monday is 0)一周第几天注意星期一是第0天

Julian day (day in the year, 1-366)一年第几天,从1开始计

DST (Daylight Savings Time) flag (-1, 0 or 1)是否是夏令时,0代表不是,1代表是

例子

time.struct_time(tm_year=2017, tm_mon=12, tm_mday=31, tm_hour=23, tm_min=27, tm_sec=2, tm_wday=6, tm_yday=365, tm_isdst=0)

4、time模块的几个变量

4.1 timezone

表示世界标准时间utc和本地时间的差值,单位为秒。中国的时区比时间标准时间快8小时。

utc - (utc+8)

>>> time.timezone

-28800

>>> 28800/3600

8.0

4.2 altzone

UTC和本地夏令时直接的差值,单位为s 我们不使用夏令时,所以此处不做深究,了解即可

>>> time.altzone #夏令时和utc的时间差值

-32400

4.3 time.daylight

是否使用了夏令时,0为不使用

>>> time.daylight 是否使用了夏令时

0

5、time的函数

5.1 time.time() 获取时间戳

此处获取的时间戳为utc标准时间与1970的时间间隔。

5.2 time.sleep()

延时多少秒,单位为秒

5.3 time.gmtime() 

gmtime() -- convert seconds since Epoch to UTC tuple

将时间戳转换为utc时间

5.4 time.localtime()

localtime() -- convert seconds since Epoch to local time tuple

将时间戳转换成本地时间

>>> time.time()

1520614121.487381

>>> time.gmtime(time.time())

time.struct_time(tm_year=2018, tm_mon=3, tm_mday=9, tm_hour=16, tm_min=49, tm_sec=4, tm_wday=4, tm_yday=68, tm_isdst=0)

>>> time.localtime(time.time())

time.struct_time(tm_year=2018, tm_mon=3, tm_mday=10, tm_hour=0, tm_min=49, tm_sec=14, tm_wday=5, tm_yday=69, tm_isdst=0)

>>>

此程序的说明:注意time.gmtime()与time.localtime()的对比

Time.time()为获取一个时间戳,需要明确 时间戳其实就是utc与1970的时间差

Time.gmtime(time.time())将时间戳转换为utc九元组

Time.localtime(time.time())将时间戳转换为本地时间的九元组,实际就是转换为标准的九元组后,根据timezone进行换算的

5.5 如何取用时间struct_time-9元组的值

时间元组赋值给变量,变量用.来引用

import time

x=time.gmtime()

print(x)

print(x.tm_year,x.tm_yday)
----------------------------------------
time.struct_time(tm_year=2018, tm_mon=2, tm_mday=26, tm_hour=17, tm_min=22, tm_sec=23, tm_wday=0, tm_yday=57, tm_isdst=0) 2018 57

5.6  strftime() 

将元组转换为标准格式输出

这里的元组默认为localtime,如果给出元组,则从元组中取值

Time.strftime(格式,元组)

>>> time.strftime('%Y %m %d %X')

'2018 02 10 01:21:43'

5.7 strptime()

将文本格式转换为元组

Time.strptime(文本,格式)

>>> time.strptime('2018 02 10 01:21:43','%Y %m %d %X')

time.struct_time(tm_year=2018, tm_mon=2, tm_mday=10, tm_hour=1, tm_min=21, tm_sec=43, tm_wday=5, tm_yday=41, tm_isdst=-1)

>>>

注意:tm_isdst这个部分,转换之后夏令时为-1

5.8 Time.ctime(时间戳)

会转换为本地时区的 文本形式时间

>>> time.ctime(time.time())#默认传入time.time()

'Sat Mar 10 01:31:45 2018'                                         

5.9 Time.asctime(time.localtime())默认传入localtime

从元组取值转换成固定的格式输出,和strftime类似

>>> time.asctime(time.gmtime())

'Fri Mar  9 17:33:26 2018'

>>> time.asctime(time.localtime())

'Sat Mar 10 01:33:32 2018'

>>> time.asctime()

'Sat Mar 10 01:33:39 2018'

5.10 time.mktime() -- convert local time tuple to seconds since Epoch

本地的时间的元组转换为时间戳

Localtime->转换为标准的时间戳->utc->local

>>> time.localtime(time.mktime(time.localtime()))

time.struct_time(tm_year=2018, tm_mon=3, tm_mday=10, tm_hour=1, tm_min=37, tm_sec=31, tm_wday=5, tm_yday=69, tm_isdst=0)

>>>

5.11 tzset() -- change the local timezone

改变timezone变量,调整时区,一般不使用

三、datetime模块的使用

1、获取当前时间的方法 datetime.datetime.now()

以字符串形式输出

print(datetime.datetime.now())当前时间

2018-01-04 02:11:37.867479

2、知道datetime.datetime.now()的类型

<class 'datetime.datetime'>

3、定义输出格式 与strftime结合

print(datetime.datetime.now())

print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
----------------------------------------- 2018-03-10 09:46:28.106559 2018-03-10 09:46:28

4、str格式时间转成datetime.datetime类

d1 = datetime.datetime.strptime('2015-03-05 17:41:20', '%Y-%m-%d %H:%M:%S')

d2 = datetime.datetime.strptime('2015-03-02 17:31:20', '%Y-%m-%d %H:%M:%S')

Print(d1)
-------------------------------- 2015-03-05 17:41:20

5、计算时间差的方法

for i in range(20):

   d3 = datetime.datetime.now()

   print(d3-d1)

   time.sleep(1)
---------------------------------- 2015-03-05 17:41:20 1100 days, 16:05:16.123119

6、与time.timedelta()结合计算时间

print(d1+datetime.timedelta(3)) 三天后的时间

print(d1+datetime.timedelta(-3)) 三天前的时间

Primt(datetime.now+datetime.timedelta(hour=3)) 三小时后的时间

Primt(datetime.now+datetime.timedelta(second0=-3)) 三秒前的时间

7、时间的修改与替换

nownow=datetime.datetime.now()

print(type(nownow))

nownow.replace(year=1999)

print(nownow,nownow.replace(year=1999))

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

 <class 'datetime.datetime'>

2018-01-04 02:31:29.952321 1999-01-04 02:31:29.952321

  注意:除非重新赋值给新的变量 不然replace不会去改变变量本身 和字符串类似

四、random 模块,随机数模块的使用

1、random.random()

生成随机浮点数范围在0-1之间 包括0不包括1

>>> random.random()
0.11288859525093142

2、random.randint()

生成随机整数,前数字都包含,即生成的随机数前后数字都可能出现

>>> random.randint(1,4)
1
>>> random.randint(1,4)
3
>>> random.randint(1,4)
4

3、random.randrange()

顾头不顾尾的range,可以设置步长,不设置step 则step为1.

randint不能设置步长step

>>> random.randrange(0,11,2)
4
>>> random.randrange(0,11,2)
8
>>> random.randrange(0,11,2)
0

4、random.choice()

放入一个非空序列 列表 字符串 元组(有序的,放入字典、集合会报错)

>>> random.choice((1,2,3,4)) #元组
3
>>> random.choice((1,2,3,4))
2
>>> random.choice(['a','b','c'])
'c'
>>> random.choice(['a','b','c'])
'a'
>>> random.choice('python') #字符串
'y'
>>> random.choice('python')
'o'

5、random.sample()取多个,与choice类似,choice取1个,sample取多个

放入一个非空序列,第二个参数表示抽取多少个,组成列表

>>> random.sample(['a','b','c'],2)
['b', 'c']
>>> random.sample('python',6)
['o', 't', 'h', 'p', 'y', 'n']

6、random.uniform() 指定区间的浮点数

和random.random做对比 random只是0和1之间

>>> random.uniform(1,4)
1.5855347763788947
>>> random.uniform(1,4)
3.890550444129729

7、洗牌功能 random.shuffle()对列表进行乱序

同时要注意是他可以直接改变列表 不需要重新赋值出来

>>> a=[1,2,3,4]
>>> random.shuffle(a)
>>> a
-----------------------------
[4, 1, 3, 2]

8、生成验证码的程序一则

思路

random.randint(0-9)

random.randint(65-90)

Chr(数字)->字符

字符串相加 ‘abc’+’d’=’abcd’

def yanzheng():
yanzhengma=''
for i in range(4):
shuzi_or_zimu = random.randint(0, 1)
if shuzi_or_zimu:
yanzhengma+=str(random.randint(0,9))
else:
yanzhengma+=chr(random.randint(65,90))
print(yanzhengma)
for i in range(5):
yanzheng()
----------------------------

1F47
YR31
R80M
66FG
F6GS 

五、os模块

os模块分两个部分来讲:1、 常用函数 2、os.path

(一)os的常用函数

1、os.getcwd() 相当于pwd

获取当前python程序运行的路径 你这个.py文件在哪 他就显示哪

2、os.chdir()

相当于linux的cd 到相应目录项进行操作

注意的是chdir的时候

对于目录\的两种处理方式

2.1、\\

2.2、r

>>> os.getcwd()
'C:\\Users\\Raytine'
>>> os.chdir('d:\')
File "<stdin>", line 1
os.chdir('d:\') ^
SyntaxError: EOL while scanning string literal
>>> os.chdir('d:\\')
>>> os.getcwd()
'd:\\'
>>> os.chdir(r'c:\')
File "<stdin>", line 1
os.chdir(r'c:\') ^
SyntaxError: EOL while scanning string literal
>>> os.chdir(r'c:\\')
>>> os.chdir(r'c:\a')
>>> os.getcwd()
'c:\\a'

注意:为什么>>> os.chdir(r'c:\')报错 ,os.chdir(r'c:\')

3、os.curdir 当前目录  os.pardir 上一级目录

>>> os.curdir #只是个变量,并不能引用
'.'
>>> os.curdir
'.'
>>> os.pardir

注意点:  os.curdir 和os.pardir 都没有()引用,不是函数

4、os.makedirs(r'c:\a\b\c') 递归创建

5、os.removedirs(r'c:\a\b\c')递归删除

删除原则:目录为空继续删,不能用来删文件及删除非空目录

>>> os.removedirs(r'c:\a\b\1.txt')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "D:\Python36\lib\os.py", line 238, in removedirs
rmdir(name)
NotADirectoryError: [WinError 267] #目录名称无效。: 'c:\\a\\b\\1.txt'
>>> os.removedirs(r'c:\a\b\c')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "D:\Python36\lib\os.py", line 238, in removedirs
rmdir(name)
OSError: [WinError 145] #目录不是空的。: 'c:\\a\\b\\c'
>>> os.removedirs(r'c:\a\b\c')

6、os.mkdir() 创建目录

不会递归,如果前面不存在则创建不成功

7、os.rmdir()删除目录

不会递归,为空删除

8、os.listdir(os.curdir)

列出文件夹下面的所有文件 以列表形式列出

>>> os.listdir('.')
['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'python.pdb' ]

9、os.remove('filename') 删除文件

10、os.rename('oldname','newname')

可以改文件夹名字以及文件的名字

>>> os.makedirs(r'c:a\b\c\d')
>>> os.rename(r'c:a\b\c\d',r'c:a\b\c\e')

11、os.stat() 查看文件的属性

>>> os.stat(r'c:a\b\c\e')
os.stat_result(st_mode=16895, st_ino=1125899906960658, st_dev=2766884258, st_nlink=1, st_uid=0, st_gid=0, st_size=0, st_atime=1519743765, st_mtime=1519743765, st_ctime=1519743765)

12 os.sep 路径分隔符 windows \\ linux /

13 os.linesep 换行符 windows \r\r linux \n

14 os.pathsep 分割文件路径的分隔符 ;

>>> os.pathsep
';'
>>> os.linesep
'\r\n'
>>> os.sep
'\\'
>>>

注意点:都没有括号引用

15、os.environ 输出系统的环境变量 为一个字典

和sys.path 不同 sys.path为python的环境变量

environ({'ALLUSERSPROFILE': 'C:\\ProgramData', 'APPDATA': 'C:\\Users\\linyuming.ESG\\AppData\\Roaming', 'WINDIR': 'C:\\Windows'})

16.os.name 系统名称

windows 为‘nt’  获取系统name针对不同系统做不同操作,增加兼容性

Windows,它是'nt',而对于Linux/Unix用户,它是'posix'。

>>> os.name
'nt'

17.os.system() 用来执行系统指令

>>> os.system('dir')

驱动器 D 中的卷没有标签。
卷的序列号是 D2E8-6B21
D:\Python36 的目录 2017/12/19 02:50 <DIR> . 2017/12/19 02:50 <DIR> .. 2017/12/19 02:50 <DIR> DLLs 2017/12/19 02:50 <DIR> Doc 2017/12/19 02:48 <DIR> include2017/12/19 02:50 <DIR> libs

(二)os.path 模块

1、os.path.abspath()

获取文件的绝对路径

2、os.path.split() 切割文件路径

切割成目录+文件的形式

print(os.path.split(r'c:\a\b\c\d')) #不论文件是否存在
('c:\\a\\b\\c', 'd')# 返回二元组,第一部分为目录 第二部分为文件名
#Split=dirname+basename

3、os.path.dirname(r'c:\a\b\c\d.txt')获取文件的目录

不论这个文件是否存在,实质就是切割路径

4 、os.path.basename(r'c:\a\b\c\d.txt') 获取文件名

这个和dirname相对,basename只取文件名

>>> os.path.dirname(r'c:\a\b\c\d.txt')
'c:\\a\\b\\c'
>>> os.path.basename(r'c:\a\b\c\d.txt')
'd.txt'
>>> os.path.split(r'c:\a\b\c\d.txt')
('c:\\a\\b\\c', 'd.txt')
#linux windows 对于路径分隔符定义不通 所以运行结果有区别
#上面的路径都可以不存在

5、os.path.exists()判断路径是否存在

可以判断文件 或者文件夹

>>> os.path.exists(r'c:\a\b\c\d.txt')
False

6、os.path.is* 判断

>>> os.path.isfile(r'c:\a\123')
False #文件不存在 false
>>> os.path.isfile(r'c:\a\b')
False #不是文件 false
>>> os.path.isfile(r'c:\a\b\1.txt')
True #存在且是文件 true
>>> os.path.isabs(r'c:\\')
True
>>> os.path.isabs(r'c:')
False #写的格式不对,不是绝对路径则返回false
>>> os.path.isabs(r'c:\\ajsdfiouoiw')
True #不存在也返回true

isabs(s)

Test whether a path is absolute

isdir = _isdir(path, /)

Return true if the pathname refers to an existing directory.

isfile(path)

Test whether a path is a regular file

islink(path)

Test whether a path is a symbolic link.

This will always return false for Windows prior to 6.0.

ismount(path)

Test whether a path is a mount point (a drive root, the root of a

share, or a mounted volume)

7、os.path.join 将多个名字组合成路径

拼接过程不能带分割符 不然会出现问题

>>> os.path.join('root','tmp','abc')
'root/tmp/abc'
>>> os.path.join(r'/','root','tmp','abc')
'/root/tmp/abc'

8、getatime/getctime获取文件的时间

>>> time.localtime(os.path.getatime(r'c:\a\b\1.txt'))
time.struct_time(tm_year=2018, tm_mon=2, tm_mday=27, tm_hour=23, tm_min=33, tm_sec=57, tm_wday=1, tm_yday=58, tm_isdst=0) os.path.getatime(file) #输出最近access访问时间1318921018.0 os.path.getctime(file) #输出文件create创建时间 os.path.getmtime(file) #输出最近修改时间
#返回的是时间戳

六、sys模块-和解释器相关的信息及操作

该部分内容较少。

sys.version 获取python解释器的版本信息

sys.stdout 标准输出

sys.argv 获取参数 第一个参数是py文件路径

sys.exit()标准退出exit(0)

print(sys.version)#输出python的信信息
print(sys.argv)#用来获取参数 第一个元素是程序路径 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
['F:/my_python_file/20180113_sys_shutil.py']

python笔记-6(import导入、time/datetime/random/os/sys模块)的更多相关文章

  1. python笔记-1(import导入、time/datetime/random/os/sys模块)

    python笔记-6(import导入.time/datetime/random/os/sys模块)   一.了解模块导入的基本知识 此部分此处不展开细说import导入,仅写几个点目前的认知即可.其 ...

  2. python 常用模块之random,os,sys 模块

    python 常用模块random,os,sys 模块 python全栈开发OS模块,Random模块,sys模块 OS模块 os模块是与操作系统交互的一个接口,常见的函数以及用法见一下代码: #OS ...

  3. Python常用模块(time, datetime, random, os, sys, hashlib)

    time模块 在Python中,通常有这几种方式来表示时间: 时间戳(timestamp) :         通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量.我们运 ...

  4. 常用模块之 time,datetime,random,os,sys

    time与datetime模块 先认识几个python中关于时间的名词: 时间戳(timestamp):通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量.我们运行“ty ...

  5. Day 17 time,datetime,random,os,sys,json,pickle

    time模块 1.作用:打印时间,需要时间的地方,暂停程序的功能 时间戳形式 time.time() # 1560129555.4663873(python中从1970年开始计算过去了多少秒) 格式化 ...

  6. time,datetime,random,os,sys,hashlib,logging,configparser,re模块

    #-----time模块----- print(help(time)) #打印time帮助文档 print(time.time()) #打印时间戳 1569824501.6265268 time.sl ...

  7. python基础语法11 内置模块time,datatime,random,os,sys,hashlib模块

    time模块 在python的三种时间表现形式: 1.时间戳: 给电脑看的. - 自1970-01-01 00:00:00到当前时间,按秒计算,计算了多少秒. 2.格式化时间(Format Strin ...

  8. CSIC_716_20191116【常用模块的用法 time ,datetime, random, os, sys, hashlib】

    import time import datetime import os import sys import random import hashlib time模块 时间戳(Timestamp) ...

  9. day25-2 random,os,sys模块

    目录 random 为什么要有random模块,random模块有什么用 os 为什么要有os模块,os模块有什么用 sys 为什么要有sys模块,sys模块有什么用 random import ra ...

随机推荐

  1. Python - openpyxl 读写操作Excel

    openpyxl特点   openpyxl(可读写excel表)专门处理Excel2007及以上版本产生的xlsx文件,xls和xlsx之间转换容易 注意:如果文字编码是“gb2312” 读取后就会显 ...

  2. Redis之哈希类型命令

    Hash(哈希) Redis hash 是一个string类型的field和value的映射表,hash特别适合用于存储对象. Redis 中每个 hash 可以存储 232 - 1 键值对(40多亿 ...

  3. Android 7.0真实上手体验

    Android 7.0真实上手体验 Android 7.0的首个开发者预览版发布了,支持的设备只有Nexus6.Nexus 5X.Nexus 6P.Nexus 9.Nexus Player.Pixel ...

  4. Java compiler level does not match the version of the installed Java project facet.解决方法

    右键项目“Properties”,在弹出的“Properties”窗口左侧,单击“Project Facets”,打开“Project Facets”页面. 在页面中的“Java”下拉列表中,选择相应 ...

  5. hdu2087kmp

    一块花布条,里面有些图案,另有一块直接可用的小饰条,里面也有一些图案.对于给定的花布条和小饰条,计算一下能从花布条中尽可能剪出几块小饰条来呢?  Input输入中含有一些数据,分别是成对出现的花布条和 ...

  6. GDI+ DrawString字间距问题

    ///   <summary> ///   绘制任意间距文字 /// </summary> ///   <param   name= "text "& ...

  7. spring cloud学习(四) Fegin 的使用

    Feign 的使用 什么是Feign? Feign : Declarative REST clients. Feign 是一个声明web服务客户端,这便得编写web服务客户端更容易,使用Feign 创 ...

  8. httpclient http状态管理

    HTTP状态管理 最初,Htt被设计成一个无状态的面向请求响应的协议,所以它不能再逻辑相关的http请求/响应中保持状态会话. 由于越来越多的系统使用http协议,其中包括http从来没有想支持的系统 ...

  9. RTU命令设置笔记

    YN+12VCTL=1 配置+12V输出控制模式:永久输出YN+5VCTL=1 配置+5V输出控制模式:永久输出 YN+GETDATA 读取采样值 YN++LIST 获取设置参数列表 YN+LOAD ...

  10. Spring MVC和Spring Data JPA之按条件查询和分页(kkpaper分页组件)

    推荐视频:尚硅谷Spring Data JPA视频教程,一学就会,百度一下就有, 后台代码:在DAO层继承Spring Data JPA的PagingAndSortingRepository接口实现的 ...