Python time、os、random、json、pickle 常用模块1

今日内容:

一、常用模块 2019.04.10 更新

  • 1.time:时间
  • 2.calendar:日历
  • 3.datetime:可以运算的时间
  • 4.sys:系统
  • 5.os:操作系统
  • 6.os.path:系统路径操作
  • 7.random:随机数
  • 8.json:序列化
  • 9.pickle:序列化

二、常用模块2 2019.04.11 更新

  • 1.shutil:可以操作权限的处理文件模块
  • 2.shelve:可以用字典存取数据到文件
  • 3.标准输入输出错误流
  • 4.日志模块
  • 5.项目开发结构

------1.time模块------

常用的有这几种方式来表示时间:
    1.时间戳:time.time()
    2.(指定时间戳下的)当前时区时间:time.localtime()
    3.(指定时间戳下的)格林威治时间:time.gmtime()
    4.(指定时间元组下的)格式化时间:time.strftime(fmt[,tupletime])
import time

# 今天(2019.04.10)的时间戳,计算时间是从1970年1月1日开始
print(time.time())  # 1554878880.2359598

# 睡眠或者说,停止运行(其实是进入循环了)一段时间
time.sleep(seconds)  # time.sleep(2)

# time.struct_time(tm_year=2019, tm_mon=4, tm_mday=10, tm_hour=14,
# tm_min=53, tm_sec=37, tm_wday=2, tm_yday=100, tm_isdst=0) (一行太长了,手动分两行)
print(time.localtime())

# 可以将得到的时间戳放进参数列表中,可以格式化返回
# time.struct_time(tm_year=2019, tm_mon=4, tm_mday=10, tm_hour=14,
# tm_min=48, tm_sec=0, tm_wday=2, tm_yday=100, tm_isdst=0)
print(time.localtime(1554878880.2359598))

# 2019-04-10 15:03  按照格式输出时间样式
print(time.strftime("%Y-%m-%d %H:%M"))

# 2019-04-10 15:07:04
print(time.strftime("%Y-%m-%d %H:%M:%S"))

# 19-04-10 15:08 Wed
print(time.strftime("%y-%m-%d %H:%M %a"))

# 2019-04-10 03:08 Wednesday
print(time.strftime("%Y-%m-%d %I:%M %A"))

# 2019-04-10 03:10 PM 04/10/19 100 
print(time.strftime("%Y-%m-%d %I:%M %p %x %j "))


# 以下为格式中规定的关键词格式:
%y 两位数的年份表示(00-99)
%Y 四位数的年份表示(000-9999)
%m 月份(01-12)
%d 月内中的一天(0-31)
%H 24小时制小时数(0-23)
%I 12小时制小时数(01-12)
%M 分钟数(00=59)
%S 秒(00-59)
%a 本地简化星期名称
%A 本地完整星期名称
%b 本地简化的月份名称
%B 本地完整的月份名称
%c 本地相应的日期表示和时间表示
%j 年内的一天(001-366)
%p 本地A.M.或P.M.的等价符
%U 一年中的星期数(00-53)星期天为星期的开始
%w 星期(0-6),星期天为星期的开始
%W 一年中的星期数(00-53)星期一为星期的开始
%x 本地相应的日期表示
%X 本地相应的时间表示
%Z 当前时区的名称
%% %号本身

------2.calendar:日历------

import calendar

"""
判断闰年:calendar.isleap(year)
查看某年某月日历:calendar.month(year, mouth)
查看某年某月起始星期与当月天数:calendar.monthrange(year, mouth)
查看某年某月某日是星期几:calendar.weekday(year, month, day)
"""
# False
print(calendar.isleap(2018))  # 判断输入的年份是不是闰年
# 自己手撸一个
# 分析:能被400整除的年份为闰年,能为4整除并且不能为100整除的也是闰年,其他的都不是
def my_isleap(num):
    if num % 400 == 0:
        return True
    if num % 4 == 0 and num % 100 != 0:
        return True
    return False

res = my_isleap(2018)
print(res)  # False
print(calendar.month(2018, 10))
"""
# 打印结果如下:
"""
    October 2018
Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7
 8  9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
"""

------3.datetime:可以运算的时间------


当前时间:datetime.datetime.now()
昨天:datetime.datetime.now() + datetime.timedelta(days=-1)
修改时间:datetime_obj.replace([...])
格式化时间戳:datetime.date.fromtimestamp(timestamp)


import datetime
# 2019-04-10 15:21:31.775391
print(datetime.datetime.now())  # 直接打印当前时间

# 昨天 2019-04-09 15:23:51.948908
res = datetime.datetime.now() + datetime.timedelta(days=-1)
print(res)

# 当前时间 2019-04-09 15:25:00.728168  其实在上面也被延后了一天了
# 改时间 2018-04-09 15:25:00.728168
res = res.replace(year=2018)
print(res)


# 打印结果:2019-04-10 
res = datetime.date.fromtimestamp(1554878880.2359598)
print(res)

------4.sys:系统------

import sys

# 命令行打印运行程序的路径
# ['D:/fullstack_07/day17/time时间.py']
print(sys.argv)

# 退出程序,下面的代码就不会执行了
# print(sys.exit(0))

# 上面的代码一定要注释掉啊,不然下面的代码是不会执行的
# 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 16:02:32)(后面还有一堆,不复制了)
print(sys.version)

# 最大的数字 9223372036854775807
print(sys.maxsize)
# 其实再大也是可以,这里只是设置的一个界限,
# Python3中是以字符串的形式存储数字
# Python2中有int型和long之分

# ['D:\\fullstack_07\\day17', 'D:\\fullstack_07', ...]
# 环境变量的值
print(sys.path)

# win32 显示操作系统的平台名称
print(sys.platform)

------5.os:操作系统------

import os

# 生成单级目录
os.mkdir('aaa')

# 生成多级目录
os.makedirs('aaa/b/c')

# 注意:练习的时候,生成完要注释代码,不然会报错

# 将第一次生成的 aaa 改成 aa
os.rename('aaa', 'aa')

# 打印当前工作目录
# D:\fullstack_07\day17
print(os.getcwd())

# 删除单层空目录
os.rmdir('aa/b/c')

# 移除多层空目录
os.removedirs('aa/b')

# 列举目录下所有资源
# ['00 今日内容.py', 'time时间.py']
print(os.listdir(r'D:\fullstack_07\day17'))

# 打印的就是: \
# (具有通用性,在不同的操作系统下,打印不同种的路径分隔符)
print(os.sep)

# 打印:
# 没打错啊,就是一个换行符
res = str(os.linesep)
print(res)

# 打印:;   打印一个分号,可以用作添加系统环境变量
print(os.pathsep)

# 操作系统名:nt
# 反正我是打印这个,不太懂,后期查了再更新
print(os.name)

# environ({'PROCESSOR_IDENTIFIER':
# 'Intel64 Family 6 Model 60 Stepping 3, GenuineIntel'
# 太长了,就截了前面一小段
print(os.environ)

# 执行shell脚本
# 切换到D盘下
os.system(r'D:\\')

------6.os.path:系统路径操作------

# D:/fullstack_07/day17/time时间.py
print(__file__)

# 返回path规范化的绝对路径
# D:\fullstack_07\day17
print(os.path.abspath(r'D:\fullstack_07\day17'))

# 将path分割成目录和文件名二元组返回
# ('D:\\fullstack_07\\day17', 'time时间.py')
# 相当于rsplit('\') 从右开始对字符串进行切分
res = os.path.split(r'D:\fullstack_07\day17\time时间.py')
print(res)


# 上一级目录
# D:\fullstack_07\day17
res = os.path.dirname(r'D:\fullstack_07\day17\time时间.py')
print(res)

# 最后一级名称
#  time时间.py
res = os.path.basename(r'D:\fullstack_07\day17\time时间.py')
print(res)

# 指定路径是否存在
# True
res30 = os.path.exists(r'D:\fullstack_07\day17\time时间.py')
print(res30)

# 是否是绝对路径
# True
res31 = os.path.isabs(r'D:\fullstack_07\day17\time时间.py')
print(res31)

# 是否是文件
# True
res32 = os.path.isfile(r'D:\fullstack_07\day17\time时间.py')
print(res32)

# 是否是路径
# False
res33 = os.path.isdir(r'D:\fullstack_07\day17\time时间.py')
print(res33)

# 路径拼接
# D:\fullstack_07\time时间.py
# 这样的好处在于,不同系统上的层级关系符号有差异,该方法可以避免
res34 = os.path.join(r'D:\fullstack_07', 'time时间.py')
print(res34)

# 最后存取时间
# 1554884913.360706  返回时间戳,可以作为唯一的标识
res35 = os.path.getatime(r'D:\fullstack_07\day17\time时间.py')
print(res35)

# 最后修改时间
# 1554884977.1773849
res36 = os.path.getmtime(r'D:\fullstack_07\day17\time时间.py')
print(res36)

# 目标大小
# 1168   单位是 字节
res37 = os.path.getsize(r'D:\fullstack_07\common test.py')
print(res37)

# 在Linux和Mac平台上,该函数会原样返回path,
# 在windows平台上会将路径中所有字符转换为小写,
# 并将所有斜杠转换为反斜杠。
# c:\windows\system32\
res38 = os.path.normcase('c:/windows\\system32\\')
print(res38)

# 规范化路径,如..和/
# c:\windows\Temp
res39 = os.path.normpath('c://windows\\System32\\../Temp/')
print(res39)

------7.random:随机数------

import random

# 默认随机产生(0-1)的小数
# 0.6183180335165399
ran1 = random.random()
print(ran1)

# 随机产生指定范围的一个整数例:[1,10] 闭区间
# 6
ran2 = random.randint(1, 10)
print(ran2)

# 随机产生指定范围的一个整数 例:[1,10) 前闭后开区间
# 3
ran3 = random.randrange(1, 10)
print(ran3)

# 随机产生指定范围的一个数 例:(1,10) 开区间
# 1.3022059667107808
rand4 = random.uniform(1, 10)
print(rand4)

# 单例集合 在item中随机选一个
# 15
item = [1, 'ds', 15, 'we']
rand5 = random.choice(item)
print(rand5)

# 单例集合随机选择n个
# ['we', 15]
n = 2
rand6 = random.sample(item, n)
print(rand6)

# 洗牌单列集合
item1 = [1, 'ds', 15, 'we']
# 洗牌后  ['we', 1, 15, 'ds']  
# 洗牌更改的是自身内部元素的位置
# ps: 元组不行,改不了,这个是真的改不了,因为我试了
random.shuffle(item1)
print(item1)

------8.json:序列化------

import json
# json: {} 与 [] 嵌套的数据
# 注:json中的字符串必须全部用 "" 来标识(意思是都得用双引号,用单引号是不可以的)

# 序列化:对象 --> 字符串
# 序列化成字符串 :
json_obj = {
    'a': 1,
    'b': 2,
    'c': 'df'
}
js1 = json.dumps(json_obj)
print(js1)

# {"a": 1, "b": 2, "c": "df"}

# 序列化字符串到文件中:

with open('temp.txt', 'w', encoding='utf-8') as f:
    json.dump(json_obj, f)

# 注:字符形式操作
# 反序列化对象:
js2 = json.loads(js1)
print(js2)
# {'c': 'df', 'a': 1, 'b': 2}

# 从文件读流中反序列化成对象:
with open('temp.txt','r',encoding='utf-8') as f:
    js3 = json.load(f)

print(js3)
# {'a': 1, 'b': 2, 'c': 'df'}

------9.pickle:序列化------

import pickle
"""
序列化:对象 --> 字符串
"""
pickle_obj = {
    'aa': 1,
    'bb': 2,
    'cc': 'df'
}
# 序列化成字符串:
p1 = pickle.dumps(pickle_obj)
print(p1)

# 太长了,随意切断的
# b'\x80\x03}q\x00(X\x02\x00\x00\x00aaq
# \x01K\x01X\x02\x00\x00\x00ccq\x02X\x02\x00\x00
# \x00dfq\x03X\x02\x00\x00\x00bbq\x04K\x02u.'

# 序列化字符串到文件中:
with open('temp2.txt', 'wb') as pf:
    pickle.dump(pickle_obj, pf)

# 注:字节形式操作
# 反序列化成对象:
p2 = pickle.loads(p1)
print(p2)
# {'aa': 1, 'bb': 2, 'cc': 'df'}

# 从文件中读出流数据反序列化成对象
with open('temp2.txt', 'rb') as pf:
    p3 = pickle.load(pf)

print(p3)
# {'cc': 'df', 'bb': 2, 'aa': 1}
posted @ 2019-04-10 18:21  xt12321  阅读(445)  评论(0编辑  收藏  举报