nsd1905_py02_day01

时间模块

time模块

时间表示方法

  • 时间戳:自1970-1-1 0:0:0到某一时间点之间的秒数
  • UTC时间:世界协调时。以英国格林威治这个城市所在的经度点为0时区,向东向西,每隔15度角为1个时区,全球共分为24个时区。
  • struct_time:它是一个9元组:(年、月、日、时、分、秒、一周中的第几天、一年中的第几天、是否使用夏季节约时间)
  1. >>> import time
  2. >>> time.time() # 自1970-1-1 8:0:0到执行指令间的秒数
  3. 1570843812.3590305
  4. >>> time.ctime()
  5. 'Sat Oct 12 09:31:20 2019'
  6. >>> time.ctime(0) # 参数是一个秒数
  7. 'Thu Jan 1 08:00:00 1970'
  8. >>> time.localtime() # 当前时间的struct_time
  9. time.struct_time(tm_year=2019, tm_mon=10, tm_mday=12, tm_hour=9, tm_min=33, tm_sec=10, tm_wday=5, tm_yday=285, tm_isdst=0)
  10. >>> t1 = time.localtime()
  11. >>> t1.tm_year
  12. 2019
  13. >>> t1.tm_hour, t1.tm_min
  14. (9, 33)
  15. >>> time.sleep(3) # 睡眠3秒
  16. >>> time.strftime('%Y-%m-%d %H:%M:%S') # 年-月-日 时:分:秒
  17. '2019-10-12 09:49:27'
  18. # 将时间字符串转换为9元组时间
  19. >>> t2 = time.strptime('20191001 09:50:00', '%Y%m%d %H:%M:%S')
  20. >>> t2.tm_mon
  21. >>> t2.tm_mday

datetime模块

  1. >>> from datetime import datetime
  2. >>> datetime.now() # 返回年月日时分秒毫秒
  3. datetime.datetime(2019, 10, 12, 10, 39, 47, 593038)
  4. >>> t1 = datetime.now()
  5. >>> t1.year, t1.month, t1.day, t1.hour, t1.minute, t1.second, t1.microsecond
  6. (2019, 10, 12, 10, 40, 58, 342680)
  7. >>> t1.strftime('%H:%M:%S')
  8. '10:40:58'
  9. # 将时间字符串转成datetime对象
  10. >>> t2 = datetime.strptime('20191001 09:50:00', '%Y%m%d %H:%M:%S')
  11. >>> t2
  12. datetime.datetime(2019, 10, 1, 9, 50)
  13. >>> from datetime import datetime, timedelta
  14. >>> t = datetime.now()
  15. >>> days = timedelta(days=50, hours=2)
  16. >>> t - days # 50天2小时之前
  17. datetime.datetime(2019, 8, 23, 8, 54, 5, 724316)
  18. >>> t + days # 50Gd 2小时之后
  19. datetime.datetime(2019, 12, 1, 12, 54, 5, 724316)

异常处理

  1. try:
  2. 有可能发生异常的语句块
  3. except 异常1:
  4. 解决代码1
  5. except 异常2:
  6. 解决代码2
  7. else:
  8. 不发生异常才执行的语句
  9. finally:
  10. 不管异常是否发生,都要执行的语句

主动触发异常

  • 使用raise语句,异常名称自己决定
  • 使用assert语句。一定触发AssertionError异常

os模块

  1. >>> import os
  2. >>> os.getcwd() # pwd
  3. >>> os.listdir() # ls
  4. >>> os.listdir('/tmp') # ls /tmp
  5. >>> os.mkdir('/tmp/demo') # mkdir /tmp/demo
  6. >>> os.makedirs('/tmp/mydemo/aaa') # mkdir -p /tmp/mydemo/aaa
  7. >>> os.chdir('/tmp/mydemo/aaa') # cd /tmp/mydemo/aaa
  8. >>> os.getcwd()
  9. '/tmp/mydemo/aaa'
  10. >>> os.symlink('/etc/hosts', 'zhuji') # ln -s /etc/hosts zhuji
  11. >>> os.listdir()
  12. ['zhuji']
  13. >>> os.mknod('hello.txt') # touch hello.txt
  14. >>> os.listdir()
  15. ['zhuji', 'abc', 'hello.txt']
  16. >>> os.rmdir('abc') # rmdir abc # 只能删除空目录
  17. >>> os.listdir()
  18. ['zhuji', 'hello.txt']
  19. >>> os.remove('hello.txt') # rm -f hello.txt
  20. >>> os.rename('zhuji', 'zhuji.lnk') # mv zhuji zhuji.lnk
  21. >>> os.listdir()
  22. ['zhuji.lnk']
  23. >>> os.listdir()
  24. ['zhuji.lnk']
  25. >>> os.path.abspath('zhuji.lnk') # 返回绝对路径
  26. '/tmp/mydemo/aaa/zhuji.lnk'
  27. >>> os.path.basename('/tmp/mydemo/aaa/zhuji.lnk')
  28. 'zhuji.lnk'
  29. >>> os.path.dirname('/tmp/mydemo/aaa/zhuji.lnk')
  30. '/tmp/mydemo/aaa'
  31. >>> os.path.split('/tmp/mydemo/aaa/zhuji.lnk')
  32. ('/tmp/mydemo/aaa', 'zhuji.lnk')
  33. >>> os.path.join('/tmp/mydemo/aaa', 'zhuji.lnk')
  34. '/tmp/mydemo/aaa/zhuji.lnk'
  35. >>> os.path.isabs('home/abc') # 是绝对路径吗?
  36. False
  37. >>> os.path.isfile('/etc/host') # 存在并且是文件吗?
  38. False
  39. >>> os.path.isdir('/etc') # 存在并且是目录吗?
  40. True
  41. >>> os.path.islink('/etc/grub2.cfg') # 存在并且是链接文件吗?
  42. True
  43. >>> os.path.ismount('/boot') # 存在并且是挂载点吗?
  44. True
  45. >>> os.path.exists('/home') # 存在吗?
  46. True

os.walk的使用

os.walk可以递归遍历所有目录的内容

  1. >>> import pprint
  2. >>> import os
  3. >>> result = list(os.walk('/etc/security'))
  4. >>> pprint.pprint(result)
  5. [('/etc/security',
  6. ['console.apps', 'console.perms.d', 'limits.d', 'namespace.d'],
  7. ['access.conf',
  8. 'chroot.conf',
  9. 'console.handlers',
  10. 'console.perms',
  11. 'group.conf',
  12. 'limits.conf',
  13. 'namespace.conf',
  14. 'namespace.init',
  15. 'opasswd',
  16. 'pam_env.conf',
  17. 'sepermit.conf',
  18. 'time.conf',
  19. 'pwquality.conf']),
  20. ('/etc/security/console.apps',
  21. [],
  22. ['config-util', 'xserver', 'liveinst', 'setup']),
  23. ('/etc/security/console.perms.d', [], []),
  24. ('/etc/security/limits.d', [], ['20-nproc.conf']),
  25. ('/etc/security/namespace.d', [], [])]
  26. # 分析
  27. # 1. 判断有多少项
  28. >>> len(result)
  29. 5
  30. # 列表中有5项,每项的结构相同
  31. # 2. 查看列表中的各项特点
  32. >>> result[0]
  33. ('/etc/security', ['console.apps', 'console.perms.d', 'limits.d', 'namespace.d'], ['access.conf', 'chroot.conf', 'console.handlers', 'console.perms', 'group.conf', 'limits.conf', 'namespace.conf', 'namespace.init', 'opasswd', 'pam_env.conf', 'sepermit.conf', 'time.conf', 'pwquality.conf'])
  34. >>> result[1]
  35. ('/etc/security/console.apps', [], ['config-util', 'xserver', 'liveinst', 'setup'])
  36. # 列表由元组构成
  37. # 3. 分析元组
  38. >>> f1 = result[0]
  39. >>> len(f1)
  40. 3
  41. >>> f2 = result[1]
  42. >>> len(f2)
  43. 3
  44. # 每个元组结构也完全一样,元组由3项内容构成:
  45. # (路径字符串,路径下目录列表,路径下文件列表)
  46. # 输出每个路径下的内容
  47. >>> for path, folders, files in os.walk('/etc/security'):
  48. ... print('%s:\n%s\n%s' % (path, folders, files))
  49. ... print()
  50. >>> for path, folders, files in os.walk('/etc/security'):
  51. ... print('%s:' % path)
  52. ... for d in folders:
  53. ... print(d, end='\t')
  54. ... for f in files:
  55. ... print(f, end='\t')
  56. ... print('\n')

以上内容简化:

  1. >>> alist = [('aaa', [1, 2, 3], [4, 5, 6]), ('bbb', [10, 20, 30], [40,50])]
  2. >>> for i in alist:
  3. ... print(i)
  4. ...
  5. ('aaa', [1, 2, 3], [4, 5, 6])
  6. ('bbb', [10, 20, 30], [40, 50])
  7. >>> for i in alist:
  8. ... print(i[0], i[1], i[2])
  9. ...
  10. aaa [1, 2, 3] [4, 5, 6]
  11. bbb [10, 20, 30] [40, 50]
  12. >>> for a, b, c in alist:
  13. ... print(a, b, c)
  14. ...
  15. aaa [1, 2, 3] [4, 5, 6]
  16. bbb [10, 20, 30] [40, 50]
  17. >>> for a, b, c in alist:
  18. ... print('%s:' % a)
  19. ... print(b)
  20. ... print(c)
  21. ...
  22. aaa:
  23. [1, 2, 3]
  24. [4, 5, 6]
  25. bbb:
  26. [10, 20, 30]
  27. [40, 50]
  28. >>> for a, b, c in alist:
  29. ... print('%s:' % a)
  30. ... for i in b:
  31. ... print(i, end=', ')
  32. ... print()
  33. ... for j in c:
  34. ... print(j, end=', ')
  35. ... print()
  36. ...
  37. aaa:
  38. 1, 2, 3,
  39. 4, 5, 6,
  40. bbb:
  41. 10, 20, 30,
  42. 40, 50,

pickle模块

  • 普通文件只能写入str或bytes类型的数据
  • pickle存储器可以把任意数据类型写入文件,还能无损地取出
>>> import pickle
>>> f = open('/tmp/data.txt', 'wb')
>>> shopping_list = ['apple', 'egg', 'banana']
>>> pickle.dump(shopping_list, f)
>>> f.close()

>>> import pickle
>>> f = open('/tmp/data.txt', 'rb')
>>> mylist = pickle.load(f)
>>> f.close()
>>> type(mylist)
<class 'list'>
>>> mylist
['apple', 'egg', 'banana']

练习:记账程序

记账:

date save cost balance comment
2019-10-12 0 0 10000 init
2019-10-12 0 60 9940 eat
2019-10-13 0 200 9740 buy clothes
2019-10-13 10000 0 19740 salary

数据结构的表示

>>> records = []
>>> record = ['2019-10-12', 0, 0, 10000, 'init']
>>> records.append(record)
>>> record = ['2019-10-12', 0, 100, 9900, 'eat']
>>> records.append(record)
>>> records
[['2019-10-12', 0, 0, 10000, 'init'], ['2019-10-12', 0, 100, 9900, 'eat']]
# 取出最新余额
>>> records[-1]
['2019-10-12', 0, 100, 9900, 'eat']
>>> records[-1][-2]
9900