Python—day17时间模块、系统模块、递推遍历、序列化


一、time
'''
时间戳(timestamp):time.time()
延迟线程的运行:time.sleep(secs)
(指定时间戳下的)当前时区时间:time.localtime([secs])
(指定时间戳下的)格林威治时间:time.gmtime([secs])
(指定时间元组下的)格式化时间:time.strftime(fmt[,tupletime])
'''
'''
%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 当前时区的名称
%% %号本身
'''
# 1、线程延迟运行,以秒为单位
# time.sleep(secs)
'''
import time
print(time)

print('暂停开始')
secs=1
time.sleep(secs) # 延迟线程的运行 以秒为单位
print('暂停结束')

# 2、重点:时间戳》》可以作为数据的唯一标识
# time.localtime()

# 当前时区时间:东八区(上海时区)
print(time.localtime())# 输出结果time.struct_time(tm_year=2019, tm_mon=4, tm_mday=10, tm_hour=10, tm_min=10, tm_sec=2, tm_wday=2, tm_yday=100, tm_isdst=0)
# 年
print(time.localtime()[0]) # 输出结果2019
print(time.localtime().tm_year) # 输出结果2019
# 格林威志时区
print(time.gmtime()) # 输出结果time.struct_time(tm_year=2019, tm_mon=4, tm_mday=10, tm_hour=6, tm_min=46, tm_sec=53, tm_wday=2, tm_yday=100, tm_isdst=0)

# 可以将时间戳转化为时区的time

print(time.localtime(5656565653)) # 输出结果time.struct_time(tm_year=2149, tm_mon=4, tm_mday=1, tm_hour=20, tm_min=14, tm_sec=13, tm_wday=1, tm_yday=91, tm_isdst=0)
print(time.localtime(time.time())) # 输出结果time.struct_time(tm_year=2019, tm_mon=4, tm_mday=10, tm_hour=10, tm_min=14, tm_sec=20, tm_wday=2, tm_yday=100, tm_isdst=0)

# 应用场景》》通过时间戳获得该时间戳能反映出的年月日等信息

#5656565653 指的是哪一年
print(time.localtime(5656565653).tm_year) # 输出结果 2149

# 3、格式化时间
# time.strftime()
# 格式化的字符串,时间tuple
res=time.strftime('%Y-%m-%d %j days') # 输出结果2019-04-10 100 days
print(res)

t=(2020,4,10,10,19,22,2,200,0)
res=time.strftime('%Y-%m-%d %j days',t)
print(res) # 输出结果2020-04-10 200 days# 没有确保数据的安全性,只是将元祖信息转化为时间格式的字符串



# time.strptime()
res=time.strptime('2019-04-10 10:25',"%Y-%m-%d %H:%M")
print(res) # 输出结果time.struct_time(tm_year=2019, tm_mon=4, tm_mday=10, tm_hour=10, tm_min=25, tm_sec=0, tm_wday=2, tm_yday=100, tm_isdst=-1)

二、calendar:日历

判断闰年:calendar.isleap(year)
查看某年某月日历:calendar.month(year, mouth)
查看某年某月起始星期与当月天数:calendar.monthrange(year, mouth)
查看某年某月某日是星期几:calendar.weekday(year, month, day)


# 需求:输入一个年份,判断其是否是闰年
# 1、能被400整除year%400==0
# 2、能被4整除不能被100整除 year%4==0 and year%100!=0
# 判断闰年:calendar.isleap(year)

year=int(input('year:'))
b1=year%400==0
b2=year%4==0 and year % 100 !=0
if b1 or b2:
print("是闰年")
else:
print("不是闰年")

# 判断闰年:calendar.isleap(year)

import calendar
print(calendar.isleap(year)) # 判断是否是闰年

'''
# 导入日历
# 查看某年某月日历:calendar.month(year, month)
# 查看某年某月起始星期与当月天数:calendar.monthrange(year, month)
# 查看某年某月某日是星期几:calendar.weekday(year, month, day)

import calendar
print(calendar.month(2019,4))
print(calendar.monthrange(2019,4)) # 输出结果 (0, 30) 0代表周一
print(calendar.weekday(2019,4,10)) # 输出结果 2 代表周三


三、datetime:可以运算的时间
'''
当前时间:datetime.datetime.now()
昨天:datetime.datetime.now() + datetime.timedelta(days=-1)
修改时间:datatime_obj.replace([...])
格式化时间戳:datetime.date.fromtimestamp(timestamp)
'''
# 1、当前时间:datetime.datetime.now()
import datetime
tm=datetime.datetime.now()
print(tm,type(tm)) # 输出结果 2019-04-10 15:04:08.825141 <class 'datetime.datetime'>

# 2、昨天:datetime.datetime.now() + datetime.timedelta(days=-1)

day=datetime.timedelta(days=1)
print(day,type(day)) # 输出结果1 day, 0:00:00 <class 'datetime.timedelta'>
print(tm-day) # 输出结果 2019-04-09 15:06:49.812238
day=datetime.timedelta(days=-1)
print(tm+day) # 输出结果 2019-04-09 15:06:49.812238
# 因为tm与day都是对象所以可以直接做运算

print(tm.replace(year=2022)) # 输出结果 2022-04-09 15:06:49.812238
# 因为tm是对象所以可以直接接着调用方法

print(datetime.date.fromtimestamp(5656565653) )# 输出结果2149-04-01 53是指可以改变时间的

四、sys:系统 一般设计脚本程序

'''
命令行参数List,第一个元素是程序本身路径:sys.argv
退出程序,正常退出时exit(0):sys.exit(n)
获取Python解释程序的版本信息:sys.version
最大int值:sys.maxsize | sys.maxint
环境变量:sys.path
操作系统平台名称:sys.platform
'''

# argv 脚本文件可以接收外界的参数
# 1、命令行参数List,第一个元素是程序本身路径:sys.argv

import sys
print(sys.argv) # 第一个元素就是当前的绝对路径 ['D:/fullstack_s41/day17/模块整合/2、系统模块.py']
# 2、环境变量:sys.path
print(sys.path) # 绝对路径

# 3、退出程序,正常退出时exit(0):sys.exit(n)
# print(sys.exit())# 手动退出程序,项目中一般不会使用

# 4、操作系统平台名称:sys.platform
a = 922337203685477580712321
print(a,type(a)) # 输出类型是整形 922337203685477580712321 <class 'int'>
print(sys.platform) # 输出结果 win32

五、os模块 操作系统
'''
生成单级目录:os.mkdir('dirname')
生成多层目录:os.makedirs('dirname1/.../dirnamen2')
重命名:os.rename("oldname","newname")
工作目录:os.getcwd()
删除单层空目录:os.rmdir('dirname')
移除多层空目录:os.removedirs('dirname1/.../dirnamen')
列举目录下所有资源:os.listdir('dirname')
路径分隔符:os.sep
行终止符:os.linesep
文件分隔符:os.pathsep
操作系统名:os.name
操作系统环境变量:os.environ
执行shell脚本:os.system()
'''
import os
# 1、工作目录:os.getcwd()
print(os.getcwd()) # 输出结果当前工作目录D:fullstack_s41day17模块整合
# 2、执行文件的当前路径:__file__
print(__file__) # 输出结果当前工作的文件的绝对路径D:/fullstack_s41/day17/模块整合/2、系统模块.py
# 3、生成单级目录:os.mkdir('dirname')

# os.mkdir('111') # 不存在文件目录就新建,存在就抛异常
# 4、重命名:os.rename("oldname","newname")

# os.rename('111','222') # 重命名,
# 5、移除多层空目录:os.removedirs('dirname1/.../dirnamen')

# os.remove('222/1.py') # 删除文件目录下文件1.py文件
# os.rmdir(r'D:fullstack_s41day17模块整合222') # 删除文件夹222

# os.rmdir('aaa/bbb') # 输出结果:删除aaa下的bbb文件夹
# os.rmdir('aaa') # 输出结果:删除aaa文件夹
# 新建目录或者删除目录其都是为空才可以新建和删除

# os.mkdir('a/b/c') # a,b 单列文件夹必须存在c不存在才能新建子文件夹c,
# 6、生成多层目录:os.makedirs('dirname1/.../dirnamen2')

# os.makedirs('a/b/c') # 生成多层目录a,b可以存在,但c不能存在,全存在就会报错
# os.removedirs('a/b/c' ) # 输出结果全部删除 c是空就可以删除c,b是空那b也可以被删除,以此类推,如果b不是空下面有文件,则删除c后就会停止删除功能

print(os.sep) # 输出:
print(ascii(os.linesep)) # 输出:' '
print(os.pathsep) # 输出:; 分号
# print(os.system('dir'))
res=os.listdir(r'C:')
print(res) # 输出结果:读出C盘下所有目录其中也包含了隐藏的目录




六、os.path:系统路径操作
'''
执行文件的当前路径:__file__
返回path规范化的绝对路径:os.path.abspath(path)
将path分割成目录和文件名二元组返回:os.path.split(path)
上一级目录:os.path.dirname(path)
最后一级名称:os.path.basename(path)
指定路径是否存在:os.path.exists(path)
是否是绝对路径:os.path.isabs(path)
是否是文件:os.path.isfile(path)
是否是路径:os.path.isdir(path)
路径拼接:os.path.join(path1[, path2[, ...]])
最后存取时间:os.path.getatime(path)
最后修改时间:os.path.getmtime(path)
目标大小:os.path.getsize(path)
'''
import sys
sys.path.clear()# sys主要控制包的绝对路径

# 1、是否是路径:os.path.isdir(path)
import os.path as os_path
print(os_path.isdir(r'D:fullstack_s41day17')) # 判断是否是路径

# 2、是否是文件:os.path.isfile(path)
print(os_path.isfile(r'D:fullstack_s41day17上节复习'))

# 3、指定路径是否存在:os.path.exists(path)
print(os_path.exists(r'D:fullstack_s41day17模块整合1、时间模块.py'))

# 4、是否是绝对路径:os.path.isabs(path)
print(os_path.isabs(r'a'))
print(os_path.isabs(r'D:fullstack_s41day17模块整合'))

# 5、返回path规范化的绝对路径:os.path.abspath(path)
print(os_path.abspath(r'a')) #输出结果D:fullstack_s41day17模块整合a

# 6、将path分割成目录和文件名二元组返回:os.path.split(path)
# D:fullstack_s41day17模块整合
print(os.path.split(r'D:fullstack_s41day17模块整合')) # 输出结果('D:\fullstack_s41\day17', '模块整合')

print(os.path.split(r'D:/fullstack_s41/day17/模块整合'))# 输出结果('D:/fullstack_s41/day17', '模块整合')


print(os.path.split(r'D:fullstack_s41day17')) # 输出结果('D:\fullstack_s41', 'day17')


print(os.path.split(r'D:fullstack_s41day17\')) # 输出结果 ('D:\fullstack_s41\day17', '')

# 7、上一级目录:os.path.dirname(path)
print(os_path.dirname(os_path.dirname(r'D:fullstack_s41day17模块整合2、系统模块.py'))) # 输出结果 D:fullstack_s41day17


# 8、最后一级名称:os.path.basename(path)
print(os_path.basename(r'D:fullstack_s41统计代码量——代码代码统计.py')) # 输出结果:代码统计.py(文件夹名)


# 9、路径拼接:os.path.join(path1[, path2[, ...]])
print(os_path.join(r'D:fullstack_s41day17模块整合2、系统模块.py','a','b')) # 输出结果D:fullstack_s41day17模块整合2、系统模块.pya



# 先将项目的根目录设置为常量 -> 项目中的所有目录与文件都应该参照次目录进行导包
BASE_PATH = os_path.dirname(os_path.dirname(__file__))
print(BASE_PATH)
sys.path.append(BASE_PATH) # 输出结果D:/fullstack_s41/day17
# 重点:将项目目录添加至环境变量

# 拼接项目中某一个文件或文件夹的绝对路径
file_path=os_path.join(BASE_PATH,'模块整合','时间模块.py')
print(file_path) # 输出结果D:/fullstack_s41/day17模块整合时间模块.py

# 10、最后存取时间:os.path.getatime(path)
print(os.path.getatime(r'D:fullstack_s41day17模块整合1、时间模块.py')) # 输出结果:1554880739.668976


# 11、 辅助上传下载进度 目标大小:os.path.getsize(path)
print(os.path.getsize(r'D:fullstack_s41day17模块整合1、时间模块.py')) # 输出结果 5360



# 12、normcase函数
# 在Linux和Mac平台上,该函数会原样返回path,在windows平台上会将路径中所有字符转换为小写,并将所有斜杠转换为反斜杠。

print(os.path.normcase('c:/windows\system32\')) # 输出结果c:windowssystem32
# 通过normcase来添加项目根目录到环境变量
BASE_PATH1=os_path.normcase(os_path.join(__file__,'..','..'))
print(BASE_PATH1) # 输出结果d:fullstack_s41day17模块整合2、系统模块.py....
sys.path.append(BASE_PATH1)

# 13、normpath函数 重点
# 规范化路径,如..和/
BASE_PATH=os_path.dirname(os_path.dirname(__file__))
sys.path.append(BASE_PATH)
BASE_PATH1=os_path.normpath(os_path.join(__file__,'..','..'))
sys.path.append(BASE_PATH1)
七、递推遍历
import os
def ls(path,files=[]):
if not os.path.exists(path): # 路径是否存在
return []
if os.path.isfile(path): # 是否是文件
return [path]
# 只能是文件夹,列出文件夹下的所有文件
file_list=os.listdir(path) # 列举目录下的所有资源
for v in file_list:
file_path=os.path.join(path,v)
if os.path.isfile(file_path):
files.append(file_path)
else:
ls(file_path)
return files
res=ls(r'D:fullstack_s41day17模块整合part1pk')
print(res)

# 输出结果:文件夹下的文件['D:\fullstack_s41\day17\模块整合\part1\pk\aa.py']

八、json:序列化
# json: {} 与 [] 嵌套的数据
# 注:json中的字符串必须全部用""来标识
'''
序列化:对象 => 字符串
序列化成字符串:json.dumps(json_obj)
序列化字符串到文件中:json.dump(json_obj, write_file)

# 注:字符形式操作
反序列化成对象:json.loads(json_str)
从文件读流中反序列化成对象:json.load(read_file)
'''
import json
# 1、序列化成字符串:json.dumps(json_obj)
# 将json类型的对象与json的字符串相互转换
#{}与[]嵌套形参的数据(pytho中建议数据从{}开始)

dic={'a':1,'b':[1,2,3,4,5]}
# 序列化:将python的字典转化为字符串传递给其他语言或保存
json_str=json.dumps(dic)
print(json_str) # 输出的结果:{"a": 1, "b": [1, 2, 3, 4, 5]}

# 2、序列化字符串到文件中:json.dump(json_obj, write_file)
with open('1','w',encoding='utf-8')as w:
json.dump(dic,w) # 将dic对象转化为字符串,再写入文件
# 输出的结果:{"a": 1, "b": [1, 2, 3, 4, 5]}

# 3、反序列化成对象:json.loads(json_str)
json_str='''{"a": 1, "b": ['1', 2, 3, 4, 5]}'''
print(json_str,type(json_str)) # 输出的结果{"a": 1, "b": ['1', 2, 3, 4, 5]}<class 'str'>
json_str="{'a': 1, 'b': [1, 2, 3, 4, 5]}"
print(json_str,type(json_str)) # 输出的结果{'a': 1, 'b': [1, 2, 3, 4, 5]} <class 'str'>
json_str='''{"a": 1, "b": [1, 2, 3, 4, 5]}'''
print(json_str,type(json_str)) # 输出的结果 {"a": 1, "b": [1, 2, 3, 4, 5]} <class 'str'>
new_dic=json.loads(json_str) # json类型的字符串不认"
print(new_dic,type(new_dic)) # 输出的结果: {'a': 1, 'b': [1, 2, 3, 4, 5]} <class 'dict'>

# 4、从文件读流中反序列化成对象:json.load(read_file)
with open('1','r',encoding='utf-8')as r:
res=json.load(r)
print(res,type(res)) # 输出的结果: {'a': 1, 'b': [1, 2, 3, 4, 5]} <class 'dict'>

九、pickle:序列化
'''
序列化:对象 => 字符串
序列化成字符串:pickle.dumps(obj)
序列化字符串到文件中:pickle.dump(obj, write_bytes_file)

# 注:字节形式操作
反序列化成对象:pickle.loads(bytes_str)
从文件读流中反序列化成对象:pickle.load(read_bytes_file)
'''
import pickle
# 可以将任意类型对象与字符串进行转换
# 1、序列化成字符串:pickle.dumps(obj)
dic={'a':1,'b':[1,2,3,4,5]}
res=pickle.dumps(dic)
print(res)
# 输出的结果:转化为2进制 b'x80x03}qx00(Xx01x00x00x00aqx01Kx01Xx01x00x00x00bqx02]qx03(Kx01Kx02Kx03Kx04Kx05eu.'

# 2、序列化字符串到文件中:pickle.dump(obj, write_bytes_file)
with open('2','wb')as w:
pickle.dump(dic,w)

# 3、反序列化成对象:pickle.loads(bytes_str)
print(pickle.loads(res)) # 输出的结果:{'a': 1, 'b': [1, 2, 3, 4, 5]}

# 4、从文件读流中反序列化成对象:pickle.load(read_bytes_file)
with open('2','rb')as r:
print(pickle.load(r)) # 输出的结果:{'a': 1, 'b': [1, 2, 3, 4, 5]}




原文地址:https://www.cnblogs.com/zhouqinmei/p/10685915.html