函数使用(六)

shutil

简介

shutil 是 Python 标准库中的一个模块,名称来源于 “shell utilities”,提供了许多高级的文件和目录操作功能,是对 os 模块中文件操作功能的补充和扩展。

主要功能

  1. 文件和目录复制

    • shutil.copy(src, dst) - 复制文件
    • shutil.copy2(src, dst) - 复制文件并保留元数据(如修改时间)
    • shutil.copyfile(src, dst) - 只复制文件内容(dst必须是文件名)
    • shutil.copytree(src, dst) - 递归复制整个目录树
  2. 文件和目录移动/重命名

    • shutil.move(src, dst) - 移动文件或目录(也可用于重命名)
  3. 文件和目录删除

    • shutil.rmtree(path) - 递归删除目录及其内容(比 os.rmdir 更强大)
  4. 归档操作

    • shutil.make_archive(base_name, format, root_dir) - 创建归档文件(zip, tar等)
    • shutil.unpack_archive(filename, extract_dir) - 解压归档文件
  5. 磁盘空间

    • shutil.disk_usage(path) - 返回磁盘使用统计信息(Python 3.3+)

使用示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import shutil

# 复制文件
shutil.copy('source.txt', 'destination.txt')

# 复制整个目录
shutil.copytree('source_dir', 'backup_dir')

# 移动/重命名文件
shutil.move('old_name.txt', 'new_name.txt')

# 删除目录及其内容
shutil.rmtree('directory_to_remove')

# 创建zip归档
shutil.make_archive('backup', 'zip', 'my_folder')

# 获取磁盘空间信息
total, used, free = shutil.disk_usage('/')
print(f"Total: {total // (2**30)}GB, Used: {used // (2**30)}GB, Free: {free // (2**30)}GB")

简介

Python 的 time 模块是标准库中用于处理时间相关操作的模块,提供了各种与时间相关的函数,包括获取当前时间、时间格式转换、睡眠等待等。

获取时间戳

时间戳(Timestamp)表示从 1970年1月1日 00:00:00 UTC(纪元时间) 到现在的秒数(浮点数)。

1
2
3
4
import time

timestamp = time.time() # 返回当前时间戳(如 1630000000.123)
print(timestamp)

时间戳 ↔ 时间元组(struct_time)

  • time.localtime([secs])
    将时间戳转换为本地时间的 struct_time 对象(若不传参数,则使用当前时间)。

  • time.gmtime([secs])
    将时间戳转换为 UTC 时间的 struct_time 对象。

  • time.mktime(tuple)
    struct_time 转换回时间戳。

  • 示例

    1
    2
    3
    4
    5
    6
    7
    # 时间戳 → struct_time
    local_time = time.localtime() # 本地时间
    utc_time = time.gmtime() # UTC 时间
    print(local_time.tm_year) # 获取年份(如 2023)

    # struct_time → 时间戳
    timestamp = time.mktime(local_time)

    struct_time 是一个命名元组,包含以下属性:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    tm_year   # 年(如 2023)
    tm_mon # 月(1-12)
    tm_mday # 日(1-31)
    tm_hour # 时(0-23)
    tm_min # 分(0-59)
    tm_sec # 秒(0-59)
    tm_wday # 星期几(0-6,0是周一)
    tm_yday # 一年中的第几天(1-366)
    tm_isdst # 是否夏令时(-1/0/1)

时间格式化

  • time.strftime(format[, tuple])
    struct_time 格式化为字符串(若不传 tuple,默认使用当前时间)。

  • time.strptime(string, format)
    将字符串解析为 struct_time

  • 示例

    1
    2
    3
    4
    5
    6
    # struct_time → 字符串
    formatted = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
    print(formatted) # 输出如 "2023-08-27 14:30:00"

    # 字符串 → struct_time
    parsed_time = time.strptime("2023-08-27", "%Y-%m-%d")
  • 常见时间格式化符号表

    格式符 说明 示例
    %a 本地化的缩写星期名 Mon, Tue (英文环境下)
    %A 本地化的完整星期名 Monday, Tuesday
    %w 星期几的数字表示(0-6,0 是周日) 0 (周日), 1 (周一)
    %d 月份的日(01-31) 01, 15, 31
    %b 本地化的缩写月份名 Jan, Dec
    %B 本地化的完整月份名 January, December
    %m 月份的数字(01-12) 01, 12
    %y 无世纪的年份(00-99) 00, 23 (表示 2000, 2023)
    %Y 带世纪的完整年份 1999, 2023
    %H 24小时制的小时(00-23) 00, 23
    %I 12小时制的小时(01-12) 01, 12
    %p 本地化的上午/下午标记 AM, PM
    %M 分钟(00-59) 00, 59
    %S 秒(00-59) 00, 59
    %f 微秒(000000-999999) 000001, 999999
    %z UTC 偏移(格式为 ±HHMM,无时区则返回空) +0800, -0500
    %Z 时区名称(无时区则返回空) CST, UTC
    %j 一年中的第几天(001-366) 001, 365
    %U 一年中的第几周(00-53,周日为一周起始) 00, 52
    %W 一年中的第几周(00-53,周一为一周起始) 00, 52
    %c 本地化的日期和时间表示 Tue Aug 23 14:30:00 2023
    %x 本地化的日期表示 08/23/23, 23/08/2023
    %X 本地化的时间表示 14:30:00
    %% 字面的 % 字符 %

睡眠等待

  • time.sleep(secs)
    让程序暂停指定秒数(可以是浮点数,如 0.5 秒)。

    1
    2
    3
    print("开始等待...")
    time.sleep(2.5) # 暂停 2.5 秒
    print("等待结束!")

性能计时

  • time.perf_counter()
    返回高精度的性能计数器(用于测量短时间间隔)。

    1
    2
    3
    4
    5
    start = time.perf_counter()
    # 执行一些操作
    time.sleep(1)
    end = time.perf_counter()
    print(f"耗时: {end - start:.2f} 秒") # 如 1.00 秒
  • time.process_time()
    返回当前进程的 CPU 时间(不包括睡眠时间)。

时区处理

  • time.timezone

    本地时区(非夏令时)与 UTC 的偏移秒数(西区时区为正,东区为区为负)。

    1
    2
    import time
    print(time.timezone) # 输出如 -28800(UTC+8,表示比 UTC 早 8 小时)
  • time.altzone

    如果本地时区启用了夏令时(DST),返回夏令时下的 UTC 偏移秒数;否则与 time.timezone 相同。

    1
    print(time.altzone)  # 如 -32400(夏令时下的 UTC+9)
  • time.daylight

    检查本地时区是否启用了夏令时(DST)。

    • 0:未启用夏令时。
    • 非 0:启用夏令时(但需结合系统配置)。
    1
    print(time.daylight)  # 0 或 1

其他函数

  • time.ctime([secs])
    将时间戳转换为可读字符串(如 "Mon Aug 27 14:30:00 2023")。

    1
    print(time.ctime())  # 输出如 "Mon Aug 27 14:30:00 2023"
  • time.asctime([tuple])
    struct_time 转换为可读字符串。

简介

calendar 模块是 Python 标准库中的一个模块,提供了与日历相关的各种功能,包括生成日历、计算闰年、获取月份天数等。

主要功能

  1. 基本日历显示

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    import calendar

    # 打印某年的日历
    print(calendar.calendar(2023))

    # 打印某年某月的日历
    print(calendar.month(2023, 9))

    # 以矩阵形式返回某月的日历
    # 每行代表一周,不足的天数用0表示
    print(calendar.monthcalendar(2023, 9))
  2. 日期信息获取

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    # 判断是否是闰年
    print(calendar.isleap(2020)) # True

    # 获取两个年份之间的闰年数量
    print(calendar.leapdays(2000, 2020)) # 5

    # 获取某个月的第一天是星期几和该月的天数
    # 返回 (weekday, days)
    # 星期几: 0-6 (0是周一)
    print(calendar.monthrange(2023, 9)) # (calendar.FRIDAY, 30) 表示2023年9月1日是周五,共30天
  3. 星期相关

    1
    2
    3
    4
    5
    # 获取某天的星期几 (0-6, 0是周一)
    print(calendar.weekday(2023, 9, 1)) # 4 (周五)

    # 设置一周的第一天 (默认0-周一)
    calendar.setfirstweekday(calendar.SUNDAY) # 设置为周日
  4. TextCalendar 和 HTMLCalendar 类

    1
    2
    3
    4
    5
    6
    7
    # 创建文本日历对象
    tc = calendar.TextCalendar()
    print(tc.formatmonth(2023, 9))

    # 创建HTML日历对象
    hc = calendar.HTMLCalendar()
    print(hc.formatmonth(2023, 9))
  5. 其他实用功能

    1
    2
    3
    4
    5
    # 获取月份名称
    print(calendar.month_name[9]) # 'September'

    # 获取星期名称 (注意: 受firstweekday设置影响)
    print(calendar.day_name[calendar.weekday(2023, 9, 1)]) # 'Friday'

使用示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import calendar

# 打印当前月份的日历
year = 2023
month = 9

# 设置周日为一周的第一天
calendar.setfirstweekday(calendar.SUNDAY)

# 打印日历
print(f"{calendar.month_name[month]} {year}")
print("Su Mo Tu We Th Fr Sa")
month_days = calendar.monthcalendar(year, month)
for week in month_days:
print(" ".join(f"{day:2}" if day != 0 else " " for day in week))

简介

datetime 是 Python 标准库中用于处理日期和时间的模块,它提供了多种类来操作日期、时间、时间间隔等。

主要类

  1. datetime.date - 处理日期(年、月、日)
  2. datetime.time - 处理时间(时、分、秒、微秒)
  3. datetime.datetime - 处理日期和时间
  4. datetime.timedelta - 处理时间间隔(时间差)
  5. datetime.tzinfo - 处理时区信息(抽象基类)

常用功能

  1. date 类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    from datetime import date

    # 创建日期对象
    today = date.today() # 当前日期
    specific_date = date(2023, 5, 15)

    # 获取日期属性
    print(today.year) # 年
    print(today.month) # 月
    print(today.day) # 日

    # 日期运算
    delta = date(2023, 6, 1) - today # 计算日期差
    print(delta.days) # 相差的天数
  2. time 类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    from datetime import time

    # 创建时间对象
    t = time(14, 30, 15) # 14:30:15

    # 获取时间属性
    print(t.hour) # 时
    print(t.minute) # 分
    print(t.second) # 秒
    print(t.microsecond) # 微秒
  3. datetime 类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    from datetime import datetime

    # 获取当前日期和时间
    now = datetime.now()

    # 创建特定日期时间
    dt = datetime(2023, 5, 15, 14, 30, 15)

    # 获取属性
    print(dt.year, dt.month, dt.day) # 日期部分
    print(dt.hour, dt.minute, dt.second) # 时间部分

    # 时间戳转换
    timestamp = dt.timestamp() # 转为时间戳
    dt_from_ts = datetime.fromtimestamp(timestamp) # 从时间戳创建

    # 字符串格式化
    formatted = dt.strftime("%Y-%m-%d %H:%M:%S") # 转为字符串
    parsed = datetime.strptime("2023-05-15", "%Y-%m-%d") # 从字符串解析
  4. timedelta 类

    1
    2
    3
    4
    5
    6
    7
    8
    from datetime import datetime, timedelta

    # 时间间隔
    delta = timedelta(days=7, hours=3)

    # 日期运算
    week_later = datetime.now() + timedelta(weeks=1)
    three_days_ago = datetime.now() - timedelta(days=3)
  5. tzinfo 类

    tzinfo 是一个抽象基类,用于表示时区信息。要使用时区功能,您需要创建 tzinfo 的子类并实现其抽象方法。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    from datetime import datetime, timedelta, tzinfo

    class FixedOffset(tzinfo):
    """固定时区偏移的简单实现"""

    def __init__(self, offset_hours, name):
    self.__offset = timedelta(hours=offset_hours)
    self.__name = name

    def utcoffset(self, dt):
    return self.__offset

    def tzname(self, dt):
    return self.__name

    def dst(self, dt):
    return timedelta(0) # 不考虑夏令时

    # 使用自定义时区
    beijing_tz = FixedOffset(8, "Beijing Time")
    dt = datetime(2023, 5, 15, 14, 30, tzinfo=beijing_tz)
    print(dt) # 2023-05-15 14:30:00+08:00
  6. timezone 类

    timezone 类是 tzinfo 的子类,用于表示固定偏移的时区(即不与地理位置绑定的简单时区,如 UTC+8、UTC-5 等)。它是 tzinfo 的具体实现,适合处理没有夏令时规则的时区。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    from datetime import timezone, timedelta

    # UTC 时区 (偏移量为0)
    utc_tz = timezone.utc # 或 timezone(timedelta(0))

    # 东八区 (UTC+8:00,如北京时间)
    beijing_tz = timezone(timedelta(hours=8))

    # 西五区 (UTC-5:00,如纽约标准时间)
    ny_tz = timezone(timedelta(hours=-5))

    UTC时间与本地时间转换

    1
    2
    3
    4
    5
    6
    7
    8
    9
    from datetime import datetime, timezone, timedelta

    # 获取当前UTC时间
    utc_now = datetime.now(timezone.utc)
    print(f"UTC时间: {utc_now}") # UTC时间: 2025-07-28 06:12:32.863445+00:00

    # 转换为东八区时间
    local_time = utc_now.astimezone(timezone(timedelta(hours=8)))
    print(f"北京时间: {local_time}") # 北京时间: 2025-07-28 14:12:32.863445+08:00

简介

zoneinfo 是 Python 3.9 引入的标准库模块,用于处理时区信息。它提供了对 IANA 时区数据库(也称为 Olson 数据库)的访问,这是时区信息的权威来源。

主要特点

  1. 内置时区支持:无需第三方库即可处理时区
  2. 使用系统时区数据:默认使用操作系统的时区数据
  3. 回退机制:如果没有系统数据,可以使用第一方包 tzdata 作为数据源
  4. datetime 模块无缝集成

基本用法

  • 创建时区对象

    1
    2
    3
    4
    5
    from zoneinfo import ZoneInfo
    from datetime import datetime, timedelta

    # 创建时区对象
    tz = ZoneInfo("America/New_York")
  • 使用时区

    1
    2
    3
    4
    5
    6
    7
    # 创建带时区的 datetime 对象
    dt = datetime(2023, 4, 15, 12, 0, tzinfo=ZoneInfo("Asia/Shanghai"))
    print(dt) # 2023-04-15 12:00:00+08:00

    # 转换时区
    dt_ny = dt.astimezone(ZoneInfo("America/New_York"))
    print(dt_ny) # 2023-04-15 00:00:00-04:00
  • 可用时区

    1
    2
    3
    4
    5
    from zoneinfo import available_timezones

    # 获取所有可用时区名称
    print(available_timezones())
    # 输出类似: {'Asia/Shanghai', 'America/New_York', ...}

注意事项

  1. 数据来源
    • 优先使用系统时区数据
    • 如果没有系统数据,可以安装 tzdata 包 (pip install tzdata)
  2. 性能考虑
    • ZoneInfo 对象是不可变的,可以被安全地缓存
    • 重复使用时区对象时建议缓存而不是重复创建
  3. pytz 的区别
    • zoneinfo 是标准库,pytz 是第三方库
    • zoneinfo 的接口更符合 Python 习惯
    • pytz 需要显式调用 localizenormalize,而 zoneinfo 不需要

高级用法

  • 处理夏令时

    1
    2
    3
    4
    5
    6
    # 夏令时转换示例
    tz = ZoneInfo("America/New_York")
    dt_pre = datetime(2023, 3, 11, 1, 59, tzinfo=tz) # 夏令时开始前
    dt_post = datetime(2023, 3, 11, 3, 0, tzinfo=tz) # 夏令时开始后

    print(dt_post - dt_pre) # 输出: 1:01:00 (1小时1分钟)
  • 使用自定义时区数据

    1
    pip install tzdata

    然后 zoneinfo 会自动使用这个包作为数据源。

pytz

简介

pytz 是一个 Python 时区处理库,它提供了 Olson 时区数据库的接口,允许准确的跨平台时区计算。这个库对于需要处理不同时区的日期时间操作非常有用。

主要功能

  1. 时区支持:提供全球主要城市和地区的时区信息
  2. 时区转换:可以在不同时区之间转换日期时间
  3. 夏令时处理:自动处理夏令时(DST)转换
  4. 时区感知:创建时区感知的 datetime 对象

基本用法

  • 安装 pytz

    1
    pip install pytz
  • 常用方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    import pytz
    from datetime import datetime

    # 获取所有时区列表
    all_timezones = pytz.all_timezones

    # 获取常用时区
    utc = pytz.utc
    eastern = pytz.timezone('US/Eastern')

    # 创建时区感知的datetime对象
    dt = datetime(2023, 1, 1, 12, 0, tzinfo=pytz.utc)

    # 本地化一个原始datetime对象
    local_dt = eastern.localize(datetime(2023, 1, 1, 12, 0))

    # 时区转换
    utc_dt = local_dt.astimezone(pytz.utc)

注意事项

  1. 不要直接使用 datetime 的 tzinfo 参数

    1
    2
    3
    4
    5
    # 错误做法
    dt = datetime(2023, 1, 1, tzinfo=pytz.timezone('US/Eastern'))

    # 正确做法
    dt = pytz.timezone('US/Eastern').localize(datetime(2023, 1, 1))
  2. pytz 时区对象不等同于 Python 3.9+ 的 zoneinfo

    • pytz 有自己特殊的实现方式
    • Python 3.9+ 推荐使用标准库的 zoneinfo

与标准库的对比

Python 3.9+ 引入了 zoneinfo 模块作为时区处理的标准方式,但 pytz 仍然广泛使用,特别是在旧代码库中。主要区别:

  1. pytz 有更复杂但更精确的 DST 处理
  2. zoneinfo 更简单,与标准库集成更好
  3. pytz 需要显式调用 localize()normalize()

实际应用示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import pytz
from datetime import datetime

# 创建UTC时间
utc_time = datetime.now(pytz.utc)
print(f"UTC时间: {utc_time}") # UTC时间: 2025-07-28 06:34:11.377939+00:00

# 转换为上海时间
shanghai = pytz.timezone('Asia/Shanghai')
shanghai_time = utc_time.astimezone(shanghai)
print(f"上海时间: {shanghai_time}") # 上海时间: 2025-07-28 14:34:11.377939+08:00

# 处理夏令时
ny = pytz.timezone('America/New_York')
ny_time = utc_time.astimezone(ny)
print(f"纽约时间: {ny_time}") # 纽约时间: 2025-07-28 02:34:11.377939-04:00
本文结束 感谢您的阅读
正在加载今日诗词....