赞
踩
os
和sys
是Python标准库中两个非常重要的模块,它们提供了丰富的方法来与Python解释器以及操作系统交互。
os
模块提供了许多函数,用于处理文件和目录等操作系统任务,如路径管理、执行命令、获取进程信息等。
os.getcwd()
:返回当前工作目录的路径。os.chdir(path)
:改变当前工作目录到指定的路径。os.listdir(path='.')
:列出指定目录下的所有文件和子目录名。os.mkdir(path, mode=0o777)
:创建一个名为path的文件夹。os.makedirs(name, mode=0o777, exist_ok=False)
:递归创建目录。os.remove(path)
/ os.unlink(path)
:删除指定路径的文件。这两个方法功能相同。os.rmdir(path)
:删除空目录。os.path.join(a, *p)
:将多个路径组合后返回。sys
模块提供了一系列有关Python解释器和它的环境的函数和变量。
sys.argv
:命令行参数List,第一个元素是程序本身路径。sys.exit([arg])
:退出程序,可选参数可以是给定的返回值或错误消息。sys.version
:获取Python解释器版本信息。sys.path
:返回模块搜索路径列表。可以被修改(例如添加新路径)以影响未来模块加载行为。import os import sys print(" os模块 ".center(100, "-")) # 获取当前工作目录 current_dir = os.getcwd() print("Current Directory:", current_dir) # 列出当前目录下所有内容 , 包括文件和文件夹 print(os.listdir('.')) # 创建新目录 new_dir = "sample_directory" if not os.path.exists(new_dir): # mode = 0o777 是指定权限 ,如果文件夹存在会报错 : FileExistsError: [Errno 17] File exists: 'sample_directory' os.mkdir(new_dir, mode=0o777) print(f"Directory {new_dir} created.") # 删除目录 if os.path.exists(new_dir): os.rmdir(new_dir) print(f"Directory {new_dir} deleted.") # 改变当前工作目录 os.chdir("/Users/fangyirui/PycharmProjects/") print(os.listdir()) # 递归新目录,exist_ok 代表忽略是否已经存在 os.makedirs("sample_directory2/aa/aaa/aaa", mode=0o777, exist_ok=True) # 获取文件的绝对路径 print(os.path.abspath("xxxx")) # 获取文件的基本名称,不管文件是否存在 print(os.path.basename("/path/to/somefile.txt")) # 文件或文件夹改名 os.rename("sample_directory2", "sample_directory3") print(" sys模块 ".center(100, "-")) # 打印命令行参数 print("Script name:", sys.argv[0]) for i, arg in enumerate(sys.argv[1:], 1): print(f"Arg {i}: {arg}") # 检查Python版本号 # hasattr 方法:返回对象是否具有给定名称的属性。这是通过调用getattr(obj, name)并捕获AttributeError来完成的。 if not hasattr(sys, "hexversion") or sys.hexversion < 0x03070000: sys.exit("This script requires Python 3.7 or later") print(sys) print(sys.hexversion) print(sys.version) print(0x03070000) # 添加新搜索路径,python会在这些路径下搜索模块 new_path = "/path/to/add" if new_path not in sys.path: sys.path.append(new_path) print(sys.path) sys.exit("测试打印退出信息")
其中sys.argv在pycharm下需要以下配置才行
time
模块是Python的标准库之一,它提供了各种与时间相关的函数。这个模块对于执行时间相关的操作,如获取当前时间、延迟程序执行、测量性能等非常有用。
time.time()
:返回自纪元(Epoch,即1970年1月1日 00:00:00 UTC)以来经过的秒数。time.sleep(seconds)
:使程序暂停指定的秒数。time.localtime([secs])
:将从纪元以来的秒数转换为本地时间。如果不提供参数,则默认使用当前时间。time.gmtime([secs])
:和localtime类似,但返回UTC时区的struct_time对象。time.strftime(format[, t])
:将一个struct_time(默认为当前时间)转换为给定格式的字符串。time.strptime(string[, format])
:将格式化字符串转换回struct_time对象。import time # 获取当前时间戳 timestamp = time.time() print("Current Timestamp:", timestamp) # 将时间戳转换为本地时间 local_time = time.localtime(timestamp) print("Local Time:", local_time) # 格式化日期和时间 formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", local_time) print("Formatted Time:", formatted_time) # 程序延迟执行 print("Sleeping for 5 seconds...") time.sleep(5) print("Awake!") # 解析日期字符串 date_string = "2023-04-01" parsed_date = time.strptime(date_string, "%Y-%m-%d") print(f"Parsed Date: {parsed_date.tm_year}-{parsed_date.tm_mon}-{parsed_date.tm_mday}")
time.struct_time
对象time.struct_time
是Python中time
模块定义的一个类,用于表示时间。它是一个具有九个属性的命名元组,这些属性提供了关于日期和时间的详细信息。这种格式便于处理和存储日期时间值。
当你使用如time.localtime()
、time.gmtime()
等函数将秒数转换成本地时间或UTC时间时, 这些函数会返回一个填充了上述信息的struct_time
对象。
import time
# 获取当前本地时间,并以struct_time形式展示
local_time = time.localtime()
print(local_time)
# 输出可能类似: time.struct_time(tm_year=2023, tm_mon=4, tm_mday=15, ...)
# 访问struct_time对象中特定字段
print("Year:", local_time.tm_year)
print("Month:", local_time.tm_mon)
print("Day of the month:", local_time.tm_mday)
通过使用这种结构化方式来处理日期和时间数据,在进行比较、计算或格式化输出等操作时更加方便和直观。此外,在需要对日期和时间进行序列化或与其他系统交互时也非常有用。
datetime
模块是Python的标准库之一,提供了一系列用于处理日期和时间的类。与time
模块相比,它提供了更高级别、更灵活且易于使用的接口来操作日期和时间。这个模块支持日期和时间的算术运算,并且能够对日期和时间进行格式化输出或解析。
now()
/ today()
:获取当前本地日期或者详细到时分秒的当前本地时间。strftime(format)
:将date或者datetime对象格式化为字符串。strptime(date_string, format)
:将格式化字符串转换为date或者datetime对象。from datetime import datetime, date, time, timedelta # 获取当前完整时间 now = datetime.now() print("Current DateTime:", now) # 获取今天的日期 today = date.today() print("Today's Date:", today) # 创建特定日期和时间 some_date = date(2023, 4, 15) some_time = time(14, 30) print("Specific Date:", some_date) print("Specific Time:", some_time) # 时间加减 tomorrow = today + timedelta(days=1) # 当前日加上一天 last_week = today - timedelta(weeks=1) # 当前日减去一周 print("Tomorrow's Date:", tomorrow) print("Date Last Week:", last_week) # 格式化输出 formatted_date = now.strftime("%Y-%m-%d %H:%M:%S") print("Formatted DateTime:", formatted_date) # 解析字符串为DateTime对象 parsed_datetime = datetime.strptime(formatted_date,"%Y-%m-%d %H:%M:%S") print("Parsed DateTime:", parsed_datetime)
from datetime import datetime, timedelta def workdays(end_time, chinese_holidays_name): start_time = datetime.now() # start_time -= timedelta(days=1) work_days = 0 all_days = (end_time - start_time).days days_off = [5, 6] while start_time.date() < end_time.date(): # print(start_time, start_time.weekday()) if start_time.weekday() not in days_off: work_days += 1 start_time += timedelta(days=1) print(f"距离【{chinese_holidays_name}】还有{all_days}天,工作日有{work_days}天") holidays = { datetime(2024, 4, 4): "清明", datetime(2024, 5, 1): "五一", datetime(2024, 6, 8): "端午", datetime(2024, 9, 17): "中秋", datetime(2024, 10, 1): "国庆", datetime(2025, 1, 1): "元旦", datetime(2025, 1, 28): "春节" } for k, v in holidays.items(): workdays(k, v)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。