Python从基础到精通day6

时间相关模块

time模块

时间表示方式
  • 时间戳:表示的是从1970年1月1日00:00:00开始按秒计算的偏移量
  • UTC时间:世界协调时
  • struct_time:九元组时间(年,月,日,时,分,秒,一周中的第几天,一年中的第几天,是否使用DST夏季节约时间)
>>> import time
>>> time.time()      # 当前时间的时间戳
1587432752.0444653
>>> time.ctime()     # 当前UTC时间的字符串形式
'Tue Apr 21 09:33:08 2020'
>>> t = time.localtime()   # 当前时间的九元组时间
>>> t
time.struct_time(tm_year=2020, tm_mon=4, tm_mday=21, tm_hour=9, tm_min=34, tm_sec=29, tm_wday=1, tm_yday=112, tm_isdst=0)
>>> t.tm_yday   # 今天是一年中的第几天
112
>>> t.tm_wday   # 今天是一周中的第几天,0表示周一
1

>>> time.sleep(3)
# 将当前时间转成指定的字符串
>>> time.strftime('%Y-%m-%d %a %A %H:%M:%S')
'2020-04-21 Tue Tuesday 09:52:19'
# 将时间字符串转换成9元组时间
>>> t1 = time.strptime('2021-5-1 9:20:30', '%Y-%m-%d %H:%M:%S')
>>> t1
time.struct_time(tm_year=2021, tm_mon=5, tm_mday=1, tm_hour=9, tm_min=20, tm_sec=30, tm_wday=5, tm_yday=121, tm_isdst=-1)
>>> t2 = time.strptime('2020-5-1 9:20:30', '%Y-%m-%d %H:%M:%S')
>>> t1 > t2
True

案例1:测试计算机从1加到一千万的计算时间

import  time
date1 = time.time()
result = 0
for i in range(1,10000001):
    result += i
date2 = time.time()
data3 = date2 - date1
print(data3)

测试运行:

[root@python day6]# python3 lianxi.py
1.595163106918335

案例2:取出指定时间段的日志

[root@python ~]# cat log.txt
2019-05-15 08:10:01 aaaa
2019-05-15 08:32:00 bbbb
2019-05-15 09:01:02 cccc
2019-05-15 09:28:23 dddd
2019-05-15 10:42:58 eeee
2019-05-15 11:08:00 ffff
2019-05-15 12:35:03 gggg
2019-05-15 13:13:24 hhhh

import time
t9 = time.strptime('2019-05-15 09:00:00','%Y-%m-%d %H:%M:%S')定义启始时间,将时间转换为固定格式
t12 = time.strptime('2019-05-15 11:00:00','%Y-%m-%d %H:%M:%S')定义结束时间
with open('/root/log.txt') as fobj:
	for line in fobj:
		t = time.strptime(line[:19],'%Y-%m-%d %H:%M:%S')将每一行时间取出转换为格式为'%Y-%m-%d %H:%M:%S'
		if t > t12:
			break
		if t >= t9:
			print(line,end='')

datetime模块

>>> from datetime import datetime
>>> t = datetime.now()
>>> t  # 返回当前时间的(年,月,日,时,分,秒,毫秒)
datetime.datetime(2020, 4, 21, 10, 41, 23, 617507)
>>> t.year, t.month, t.day
(2020, 4, 21)
>>> t.hour, t.minute, t.second, t.microsecond(毫秒)
(10, 41, 23, 617507)

# 将datetime对象转成指定字符串
>>> t.strftime('%Y/%m/%d')
'2020/04/21'
# 将字符串转为datetime对象
>>> datetime.strptime('2020-4-21 10:50:00', '%Y-%m-%d %H:%M:%S')

# 计算时间差额
>>> from datetime import datetime, timedelta
>>> days = timedelta(days=100, hours=1)
>>> t = datetime.now()
>>> t
datetime.datetime(2020, 4, 21, 10, 52, 50, 982365)
>>> t - days  # 100天1小时之前的时间
datetime.datetime(2020, 1, 12, 9, 52, 50, 982365)
>>> t + days  # 100天1小时之后的时间
datetime.datetime(2020, 7, 30, 11, 52, 50, 982365)

异常

  • 当程序运行时,因为各种各样的原因出错了,那么它将崩溃,终止执行,在屏幕上抛出异常
  • 异常处理就是在代码中提前给出错误解决方案。当程序遇到问题时,要执行哪些代码进行补救
  • 异常捕获语法
try:
    有可能发生异常的语句块
except 异常1:
    异常1发生时,执行的语句块
except (异常2, 异常3):
    异常2或异常3发生时,执行的语句块
except (异常4, 异常5) as e:   # 将异常保存到变量e中
    异常4或异常5发生时,执行的语句块
else:
    异常不发生才执行的语句块
finally:
    不管异常是否发生,都要执行的语句块

案例3: 写个任意脚本练习异常处理

try:
    n = int(input('数字:'))
    result = 100 / n
    print(result)
    print('Done')
except ValueError:   #无效的值
    print('无效的值')
except EOFError:    #让用户输入的时候他按了ctrl + d 就会报 EOFError
    print('\nBye Bye')
except KeyboardInterrupt:#让用户输入的时候他按了ctrl + c 就会报KeyboardInterrupt
    print('\nBye Bye')
except ZeroDivisionError:  #0不能当被除数
    print('无效的值')

案例4,优化案例3

try:
    n = int(input('number:'))
    result = 100 / n
    print(result)
except (KeyboardInterrupt,EOFError):
    print('\n Bye Bye')
    exit()  #程序遇到exit()函数将结束,不再向下执行
except (ZeroDivisionError,ValueError) as a:
    print('无效的数字',a)
else:
    print(result) #不出现异常才执行的语句块
finally:
    print('异常语句结束') #不管异常是否发生,都要执行的语句块
print('Done')

主动触发异常

  • 使用raise主动触发指定的异常
  • assert触发AssersionError异常

案例5 raise指定异常和断言异常的使用

def get_info(name,age):
    if not 0 < age < 119:  如果年龄大与119就报错
        raise ValueError('年龄超过范围') raise主动触发指定的异常
    print('%s is %s years old' %(name,age))
   
def get_info2(name,age):
	 assert 0 < age < 120,'你活不到那么大岁数吧'  断言异常,如果判断错误就会触发异常
     print('%s is %s years old' % (name, age))
if __name__ == '__main__':
    get_info('kenji', 20)
    get_info2('kenji',130)

os模块

  • 经常与shutil一起使用
  • os模块是python访问文件系统的主要模块
>>> import os
>>> os.getcwd()        # pwd
'/root/nsd2019/nsd1911/py02/day01'
>>> os.listdir()       # ls
>>> os.listdir('/tmp') # ls /tmp
>>> os.mkdir('/tmp/demo')  # mkdir /tmp/demo
>>> os.mkdir('/tmp/nsd1911/mytest')  # 报错,不能递归创建目录
>>> os.makedirs('/tmp/nsd1911/mytest') #mkdir -p /tmp/demo
>>> os.chdir('/tmp/demo')
>>> os.getcwd()
'/tmp/demo'
>>> import shutil
>>> shutil.copy('/etc/hosts', 'hosts')
>>> shutil.copytree('/etc/security', 'security')
# ln -s /etc/passwd mima
>>> os.symlink('/etc/passwd', 'mima')  
>>> os.listdir()
['hosts', 'security', 'mima']

>>> os.environ  # 环境变量
>>> os.environ['HOME']
'/root'
>>> os.environ['PATH']
'/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin:/root/bin:/root/bin'
>>> os.remove('mima')  # rm mima
>>> os.rmdir('/tmp/nsd1911/mytest')  # 删除空目录
>>> os.stat('/etc/hosts')   # stat /etc/hosts
>>> os.chmod('/tmp/demo/hosts', 0o600)  # 权限是8进制数字
>>> os.chmod('/tmp/demo/hosts', 420)  # chmod 644

>>> os.path.abspath('hosts')  # 返回绝对路径
>>> os.path.basename('/var/tmp/abc.txt')
'abc.txt'
>>> os.path.dirname('/var/tmp/abc.txt')
'/var/tmp'
>>> os.path.split('/var/tmp/abc.txt')
('/var/tmp', 'abc.txt')
>>> os.path.join('/var/tmp', 'abc.txt')  # 拼接路径
'/var/tmp/abc.txt'

>>> os.path.isabs('/var/abc/xyz/')  # 是绝对路吗?
True
>>> os.path.isdir('/etc')   # 存在并且是目录吗?
True
>>> os.path.isfile('/etc')  # 存在并且是文件吗?
False
>>> os.path.islink('/etc/grub2.cfg')  # 存在并且是软链接吗?
True
>>> os.path.ismount('/')  # 存在并且是挂载点吗?
True
>>> os.path.exists('/etc/passwd')  # 存在吗?
True
os.walk()函数
[root@localhost nsd2019]# mkdir -p /tmp/mydemo/{aaa/bbb,ccc,ddd}
[root@localhost nsd2019]# ls /tmp/mydemo/
aaa  ccc  ddd
[root@localhost nsd2019]# ls /tmp/mydemo/aaa/
bbb
[root@localhost nsd2019]# touch /tmp/mydemo/file{01,02}
[root@localhost nsd2019]# touch /tmp/mydemo/aaa/file{03,04}
[root@localhost nsd2019]# touch /tmp/mydemo/aaa/bbb/file{05,06}
[root@localhost nsd2019]# touch /tmp/mydemo/ccc/file{07,08}
[root@localhost nsd2019]# touch /tmp/mydemo/ddd/file{09,10}
[root@localhost nsd2019]# ls -R /tmp/mydemo/
/tmp/mydemo/:
aaa  ccc  ddd  file01  file02

/tmp/mydemo/aaa:
bbb  file03  file04

/tmp/mydemo/aaa/bbb:
file05  file06

/tmp/mydemo/ccc:
file07  file08

/tmp/mydemo/ddd:
file09  file10

>>> import pprint
>>> flist = list(os.walk('/tmp/mydemo'))
>>> pprint.pprint(flist)
[('/tmp/mydemo', ['aaa', 'ccc', 'ddd'], ['file01', 'file02']),
 ('/tmp/mydemo/aaa', ['bbb'], ['file03', 'file04']),
 ('/tmp/mydemo/aaa/bbb', [], ['file05', 'file06']),
 ('/tmp/mydemo/ccc', [], ['file07', 'file08']),
 ('/tmp/mydemo/ddd', [], ['file09', 'file10'])]

# flist列表有5项,每项结构相同
>>> len(flist)
5
# 列表由元组构成
>>> flist[0]
('/tmp/mydemo', ['aaa', 'ccc', 'ddd'], ['file01', 'file02'])
# 元组又由3项构成
>>> len(flist[0])
3
# 元组中的三项是: (路径字符串,路径下目录列表,路径下文件列表)

>>> for data in os.walk('/tmp/mydemo'):
...   print(data)

>>> for lujing, mulu, wenjian in os.walk('/tmp/mydemo'):
...   print("%s:\n%s%s" % (lujing, mulu, wenjian))
...   print()

>>> for path, folders, files in os.walk('/tmp/mydemo'):
...   print('%s:' % path)
...   for mulu in folders:
...     print(mulu, end='\t')
...   for file in files:
...     print(file, end='\t')
...   print('\n')

pickle模块

  • 将各种各样的数据存入到文件中,并且可以将它们无损地取出
# 文件本身的写入方法,只能把字符串写到文件中
# 从文件中取出的也是字符串,不是列表
>>> shopping_list = ['apple', 'bananer', 'pear', 'peach']
>>> f = open('/tmp/shop.txt', 'w')
>>> f.write(shopping_list)  # 报错,只能写入字符串,列表不行
>>> f.write(str(shopping_list))
>>> f.close()
[root@localhost day01]# cat /tmp/shop.txt 
['apple', 'bananer', 'pear', 'peach']

# 使用pickle将列表存入文件
>>> import pickle
>>> f = open('/tmp/shop.data', 'wb')
>>> pickle.dump(shopping_list, f)
>>> f.close()
# 将列表从文件中取出
>>> with open('/tmp/shop.data', 'rb') as fobj:
...   l1 = pickle.load(fobj)
>>> type(l1)
<class 'list'>
>>> l1
['apple', 'bananer', 'pear', 'peach']
>>> len(l1)
4
>>> l1[0]
'apple'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值