百木园-与人分享,
就是让自己快乐。

python基础-常用内置包

  内置包是python自带的一些功能模块,有需求时可以在自己文件中直接导入使用。

 

1.datetime包

  python中的时间包,可以在业务开发中辅助我们处理时间信息;

# datetime可以获取当前时间
from datetime import datetime
re = datetime.now()
print(re)  # 2022-12-07 16:32:37.000297

# 或者
import datetime
re = datetime.datetime.now()
print(re)  # 2022-12-07 16:33:41.135512


\'\'\'
datetime可以获取时间间隔
利用timedelta方法
timedelta(days=0,seconds=0,microseconds=0,milliseconds=0,minutes=0,hours=0,week=0)  
所需的间隔参数可按需添加
一般结合datetime.datetime.now()使用
\'\'\'
# eg:获取昨天时间对象
import datetime
yesterday = datetime.datetime.now() - datetime.timedelta(days=1)  # 用加减表示时间得前后
print(yesterday)  # 2022-12-06 16:52:49.028523
print(type(yesterday))  # <class \'datetime.datetime\'>

  上面的例子中获取到的时间值都是一个datetime时间对象,不方便信息存储和传递,可以转化成字符串处理;

import datetime

now = datetime.datetime.now()
now_str = now.strftime(\'%Y-%m-%d %H:%M:%S\')
print(now_str)  # 2022-12-07 17:40:09  (这种时间格式就符合我们平常的使用和展示了)
print(type(now_str))  # <class \'str\'>

after_hour = datetime.datetime.now() + datetime.timedelta(hours=1)
print(after_hour)  # 2022-12-07 18:40:09.615895
print(after_hour.strftime(\'%Y-%m-%d %H:%M:%S\'))  # 2022-12-07 18:40:09

# 有时还需要反向操作,将时间字符串转化为datetime时间对象
# 将\'2022-12-07 17:45:09\'转化成datetime时间对象(此时字符串内的时间格式要是标准的,否则会报错)
datetime_object = datetime.datetime.strptime(\'2022-12-07 17:45:09\', \'%Y-%m-%d %H:%M:%S\')
print(datetime_object)  # 2022-12-07 17:45:09
print(type(datetime_object))  # <class \'datetime.datetime\'>
# 此时可以拿着时间对象进行时间间隔等的计算了

 

2.time包

  同样是用于处理时间、转换时间格式的模块;

\'\'\'
先看下什么是时间戳:
    英文用timestamp表示
    是1970年1月1日00时00分00秒至今的总毫秒数 (python中默认是按秒表示时间戳的)
    python中时间戳是float类型
\'\'\'
import time
# time获取当前时间戳
now_timestamp = time.time()
print(now_timestamp)  # 1670470817.385102 (返回一个秒级别的时间戳,打印的是脚本真正执行时的时间戳)
print(type(now_timestamp))  # <class \'float\'>

# 获取本地时间  time.localtime(timestamp) 
# 我们在使用time.time()获取到的时间戳并不能直观看出时间,可以借助localtime获得直观的时间格式
# 所以localtime一般用于转换时间戳为可读时间格式对象的场景
time_local = time.localtime(now_timestamp)
print(time_local)
# time.struct_time(tm_year=2022, tm_mon=12, tm_mday=8, tm_hour=11, tm_min=40, tm_sec=17, tm_wday=3, tm_yday=342, tm_isdst=0)
print(type(time_local))
# <class \'time.struct_time\'>
\'\'\'
localtime返回的是一个time时间对象
各参数简介:
    tm_year 四位年数
    tm_mon 月 1-12
    tm_mday 日 1-31
    tm_hour 0-23
    t_min 0-59
    tm_sec 秒 0-61 (闰月问题)
    tm_wday 一周中的第几天 0-6(0是周一)
    tm_yday 一年的第几日 1-366(儒略历)
    tm_isdst 夏令时 -1,0,1是否是夏时令
\'\'\'
# 不传时间戳参数 timestamp可不传(不传的时候默认使用当前时间戳)
print(time.localtime())
# time.struct_time(tm_year=2022, tm_mon=12, tm_mday=8, tm_hour=11, tm_min=41, tm_sec=22, tm_wday=3, tm_yday=342, tm_isdst=0)

# 倒退100000秒
re = time.time() - 100000
print(time.localtime(re))
# time.struct_time(tm_year=2022, tm_mon=12, tm_mday=7, tm_hour=7, tm_min=58, tm_sec=53, tm_wday=2, tm_yday=341, tm_isdst=0)


# 若想让时间戳单位和其它语言单位一致变成毫秒,直接乘1000即可
re2 = time.time() * 1000
print(re2)  # 1670471309818.359
# 暂停函数 sleep(sec)  让程序暂停sec秒数
import time
print(time.time())  # 1670471809.716068
time.sleep(5)
print(time.time())  # 1670471814.7167113 (可以看到相差了五秒)
# time.strftime(format, t) 将时间对象t转化为所要的格式
import time
# 获取当前时间的标准格式
re = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())
print(re)  # 2022-12-08 12:04:26
print(type(re))  # <class \'str\'>

# 同样有反向操作time.strptime(time_str, format)
re2 = time.strptime(\"2022-12-7 12:30\", \"%Y-%m-%d %H:%M\")
print(re2)
# time.struct_time(tm_year=2022, tm_mon=12, tm_mday=7, tm_hour=12, tm_min=30, tm_sec=0, tm_wday=2, tm_yday=341, tm_isdst=-1)
print(type(re2))
# <class \'time.struct_time\'>
# 补充下datetime生成时间戳的方法
# datetime.datetime.timestamp(datetime.datetime.now())
# 相当于将时间对象转化为时间戳格式
import datetime
print(datetime.datetime.timestamp(datetime.datetime.now()))  # 1670472569.847376

# 反向操作
print(datetime.datetime.fromtimestamp(1670472569.847376))  # 2022-12-08 12:09:29.847376
print(type(datetime.datetime.fromtimestamp(1670472569.847376)))  # <class \'datetime.datetime\'>

 

3.os包

  包含普遍的系统操作,比如路径获取、文件创建删除等;

  python基础-常用内置包

\'\'\'
os.getcwd() 获取当前路径  返回字符串
os.listdir(path)  获取指定path路径下的文件或文件夹,返回一个列表
os.makedirs(path) 创建多级文件夹
\'\'\'
import os
current_path = os.getcwd()
print(current_path)  # D:\\python_exercise

# os.makedirs(f\'{current_path}\\\\test1\\\\test2\')
# 此时当前路径下test1和test2文件夹均不存在,会同时被创建
# 如果test2存在时,会提示报错test2已存在
os.makedirs(\'test3\')  # 若只传递文件名,会自动在当前脚本所在目录下创建文件夹

print(os.listdir(current_path))
\'\'\'
[\'.idea\', \'main.py\', \'test\', \'test.py\', \'test1\', \'test2.py\', \'test5.py\', \'test6.py\', \'test7.py\', \'test_calss.py\', 
\'test_class2.py\', \'test_class3.py\', \'try_except.py\', \'tt.py\']
文件、文件夹都会被打印出来
\'\'\'
\'\'\'
os.removedirs(path)  删除空文件夹
os.rename(old_name, new_name)  给文件或文件夹重命名
os.rmdir(path)  删除空文件夹
\'\'\'
import os
# os.removedirs(\'D:\\python_exercise\\\\test1\')
\'\'\'
OSError: [WinError 145] 目录不是空的。: \'D:\\\\python_exercise\\\\test1\'
此时test1下还有test2文件夹,删除时会报错
\'\'\'
# os.removedirs(\'D:\\python_exercise\\\\test1\\\\test2\')
\'\'\'
此时test2为空文件夹,test2可以正常被删除
若test1中只有空文件夹test2,操作后test1、test2均会被删除
\'\'\'
# 同样场景test1中只有空文件夹test2
# os.rmdir(\'D:\\python_exercise\\\\test1\\\\test2\')  # 操作后test1、test2也均会被删除

# 当我们就是要删除文件夹下所有文件时,可以利用shutil库
import shutil
# shutil.rmtree(\'D:\\python_exercise\\\\test1\\\\test2\')  # test2及test2下的所有文件、文件夹均会被删除

# rename重命名
os.rename(\'D:\\python_exercise\\\\test1\', \'D:\\python_exercise\\\\test11111\')
\'\'\'
os.path.exists(path) 判断文件或路径是否存在 
os.path.isdir(path)  判断是否是文件夹
os.path.isabs(path)  判断是否是绝对路径
os.path.isfile(path)  判断是否是文件
os.path.join(path, path*) 路径字符串合并
os.path.split(path)  以层路径为基准切割
\'\'\'
import os
# 判断当前路径下是否存在test文件夹
re = os.path.exists(\'test\')
print(re)  # True
# 判断当前路径下是否存在test.py文件
re = os.path.exists(\'test.py\')
print(re)  # True
# 按绝对路径填写
re = os.path.exists(\"D:\\python_exercise\\\\test.py\")
print(re)  # True

re = os.path.isdir(\'test\')
print(re)  # True
re = os.path.isdir(\'test.py\')
print(re)  # False

re = os.path.isabs(\'test\')
print(re)  # False
re = os.path.isabs(\'D:\\python_exercise\\\\test.py\')
print(re)  # True

re = os.path.isfile(\'test\')
print(re)  # False
re = os.path.isfile(\'test.py\')
print(re)  # True


re = os.path.join(\'D:\\python_exercise\', \'test.py\')
print(re)  # D:\\python_exercise\\test.py

re = os.path.split(\'D:\\python_exercise\\\\test.py\')
print(re)  # (\'D:\\\\python_exercise\', \'test.py\')

 

4.sys包

  也是一个系统相关操作的模块;

\'\'\'
sys.modules py启动时自动加载的模块字典
\'\'\'
import sys
print(sys.modules)
\'\'\'
{\'sys\': <module \'sys\' (built-in)>, \'builtins\': <module \'builtins\' (built-in)>, 
\'_frozen_importlib\': <module \'_frozen_importlib\' (frozen)>, \'_imp\': <module \'_imp\' (built-in)>, 
\'_thread\': <module \'_thread\' (built-in)>, \'_warnings\': <module \'_warnings\' (built-in)>, 
\'_weakref\': <module \'_weakref\' (built-in)>, \'_io\': <module \'_io\' (built-in)>, 
\'marshal\': <module \'marshal\' (built-in)>, \'nt\': <module \'nt\' (built-in)>, \'winreg\': <module \'winreg\' (built-in)>, 
\'_frozen_importlib_external\': <module \'_frozen_importlib_external\' (frozen)>, \'time\': <module \'time\' (built-in)>, 
\'zipimport\': <module \'zipimport\' (frozen)>, \'_codecs\': <module \'_codecs\' (built-in)>, 
\'codecs\': <module \'codecs\' from \'D:\\\\python3.10.5\\\\lib\\\\codecs.py\'>, 
\'encodings.aliases\': <module \'encodings.aliases\' from \'D:\\\\python3.10.5\\\\lib\\\\encodings\\\\aliases.py\'>, 
\'encodings\': <module \'encodings\' from \'D:\\\\python3.10.5\\\\lib\\\\encodings\\\\__init__.py\'>, 
\'encodings.utf_8\': <module \'encodings.utf_8\' from \'D:\\\\python3.10.5\\\\lib\\\\encodings\\\\utf_8.py\'>, 
\'_signal\': <module \'_signal\' (built-in)>, \'_abc\': <module \'_abc\' (built-in)>, 
\'abc\': <module \'abc\' from \'D:\\\\python3.10.5\\\\lib\\\\abc.py\'>, \'io\': <module \'io\' from \'D:\\\\python3.10.5\\\\lib\\\\io.py\'>, 
\'__main__\': <module \'__main__\' from \'D:\\\\python_exercise\\\\main.py\'>, \'_stat\': <module \'_stat\' (built-in)>, 
\'stat\': <module \'stat\' from \'D:\\\\python3.10.5\\\\lib\\\\stat.py\'>, 
\'_collections_abc\': <module \'_collections_abc\' from \'D:\\\\python3.10.5\\\\lib\\\\_collections_abc.py\'>, 
\'genericpath\': <module \'genericpath\' from \'D:\\\\python3.10.5\\\\lib\\\\genericpath.py\'>, 
\'ntpath\': <module \'ntpath\' from \'D:\\\\python3.10.5\\\\lib\\\\ntpath.py\'>, 
\'os.path\': <module \'ntpath\' from \'D:\\\\python3.10.5\\\\lib\\\\ntpath.py\'>, 
\'os\': <module \'os\' from \'D:\\\\python3.10.5\\\\lib\\\\os.py\'>, \'_sitebuiltins\': <module \'_sitebuiltins\' 
from \'D:\\\\python3.10.5\\\\lib\\\\_sitebuiltins.py\'>, \'_codecs_cn\': <module \'_codecs_cn\' (built-in)>, 
\'_multibytecodec\': <module \'_multibytecodec\' (built-in)>, \'encodings.gbk\': <module \'encodings.gbk\' 
from \'D:\\\\python3.10.5\\\\lib\\\\encodings\\\\gbk.py\'>, \'site\': <module \'site\' from \'D:\\\\python3.10.5\\\\lib\\\\site.py\'>, 
\'__future__\': <module \'__future__\' from \'D:\\\\python3.10.5\\\\lib\\\\__future__.py\'>, 
\'itertools\': <module \'itertools\' (built-in)>, \'keyword\': <module \'keyword\' from \'D:\\\\python3.10.5\\\\lib\\\\keyword.py\'>,
 \'_operator\': <module \'_operator\' (built-in)>, \'operator\': <module \'operator\' from \'D:\\\\python3.10.5\\\\lib\\\\operator.py\'>, 
 \'reprlib\': <module \'reprlib\' from \'D:\\\\python3.10.5\\\\lib\\\\reprlib.py\'>, 
 \'_collections\': <module \'_collections\' (built-in)>, \'collections\': <module \'collections\' 
 from \'D:\\\\python3.10.5\\\\lib\\\\collections\\\\__init__.py\'>, \'types\': <module \'types\' from \'D:\\\\python3.10.5\\\\lib\\\\types.py\'>, 
 \'_functools\': <module \'_functools\' (built-in)>, \'functools\': <module \'functools\' from \'D:\\\\python3.10.5\\\\lib\\\\functools.py\'>, 
 \'importlib._bootstrap\': <module \'_frozen_importlib\' (frozen)>, \'importlib._bootstrap_external\': 
 <module \'_frozen_importlib_external\' (frozen)>, \'warnings\': <module \'warnings\' from \'D:\\\\python3.10.5\\\\lib\\\\warnings.py\'>,
  \'importlib\': <module \'importlib\' from \'D:\\\\python3.10.5\\\\lib\\\\importlib\\\\__init__.py\'>, \'importlib._abc\':
   <module \'importlib._abc\' from \'D:\\\\python3.10.5\\\\lib\\\\importlib\\\\_abc.py\'>, \'contextlib\': <module \'contextlib\' 
   from \'D:\\\\python3.10.5\\\\lib\\\\contextlib.py\'>, \'importlib.util\': <module \'importlib.util\' 
   from \'D:\\\\python3.10.5\\\\lib\\\\importlib\\\\util.py\'>, \'_struct\': <module \'_struct\' (built-in)>, \'struct\': <module \'struct\' 
   from \'D:\\\\python3.10.5\\\\lib\\\\struct.py\'>, \'six\': <module \'six\' from \'D:\\\\python3.10.5\\\\lib\\\\site-packages\\\\six.py\'>}
\'\'\'

\'\'\'
sys.path
返回当前py的环境路径列表
比如当前工作路径、python site-packages三方安装包路径等
\'\'\'
print(sys.path)
\'\'\'
[\'D:\\\\python_exercise\', \'D:\\\\python_exercise\', \'D:\\\\python3.10.5\\\\python310.zip\', \'D:\\\\python3.10.5\\\\DLLs\', 
\'D:\\\\python3.10.5\\\\lib\', \'D:\\\\python3.10.5\', \'D:\\\\python3.10.5\\\\lib\\\\site-packages\']
\'\'\'

\'\'\'
sys.exit()
退出程序
\'\'\'
# sys.exit(0)  # Process finished with exit code 0
# print(\'22\') # exit后面的内容不再执行
# sys.exit(1)  # Process finished with exit code 1


\'\'\'
sys.getdefaultencoding()
获取当前编码格式
\'\'\'
re = sys.getdefaultencoding()
print(re)  # utf-8
print(type(re))  # <class \'str\'>

\'\'\'
sys.platform
返回电脑的系统
\'\'\'
re = sys.platform
print(re)  # win32
print(type(re))  # <class \'str\'>

\'\'\'
sys.version
获取py版本
\'\'\'
re = sys.version
print(re)  # 3.10.5 (tags/v3.10.5:f377153, Jun  6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)]
print(type(re))  # <class \'str\'>

  sys.argv
    获取以python xxx.py形式在终端命令行中执行时传入的参数,结果存储于列表;
    列表的第0个元素是文件本身,后面的参数从1开始以此类推;

# python_exercise/main.py
args = sys.argv
print(args)

    在终端执行main.py文件,此时就可以拿到执行时传入的参数了,工作中很常用;

     python基础-常用内置包

 

 

总结

  python基础-常用内置包


来源:https://www.cnblogs.com/white-list/p/16963629.html
本站部分图文来源于网络,如有侵权请联系删除。

未经允许不得转载:百木园 » python基础-常用内置包

相关推荐

  • 暂无文章