ZetCode

Python time.struct_time 类

上次修改时间:2025 年 4 月 11 日

本综合指南探讨了 Python 的 time.struct_time 类,它将时间表示为一个具有九个属性的命名元组。我们将介绍时间元组的创建、操作、转换和实际示例。

基本定义

time.struct_time 类是一个时间元组,它将时间分解为九个组成部分。它由诸如 localtime()gmtime() 之类的函数返回。

这九个属性是:tm_year、tm_mon、tm_mday、tm_hour、tm_min、tm_sec、tm_wday、tm_yday 和 tm_isdst。此结构提供了一种人类可读的时间表示形式。

创建 struct_time 对象

创建 struct_time 的最简单方法是使用 localtime()gmtime() 转换时间戳。此示例显示了基本创建。

create_struct.py
import time

# Get current time as struct_time
current_time = time.localtime()
print("Current local time:", current_time)

# Get UTC time as struct_time
utc_time = time.gmtime()
print("Current UTC time:", utc_time)

# Access individual attributes
print(f"Year: {current_time.tm_year}")
print(f"Month: {current_time.tm_mon}")
print(f"Day: {current_time.tm_mday}")

此示例演示了从当前时间创建 struct_time 对象。localtime() 函数返回本地时间,而 gmtime() 返回 UTC 时间。

可以使用点表示法访问各个属性(例如,tm_year)。输出显示了时间元组的完整结构。

将 struct_time 转换为字符串

可以使用 strftime()struct_time 对象格式化为人类可读的字符串。此示例显示了各种格式化选项。

format_time.py
import time

now = time.localtime()

# Basic formatting
print(time.strftime("%Y-%m-%d %H:%M:%S", now))

# More complex formats
print(time.strftime("%A, %B %d, %Y", now))
print(time.strftime("Today is day %j of the year", now))
print(time.strftime("Local time: %I:%M %p", now))

# Using different locales (if available)
try:
    import locale
    locale.setlocale(locale.LC_TIME, 'fr_FR')
    print(time.strftime("%A %d %B %Y", now))
except:
    print("French locale not available")

strftime() 函数提供了广泛的格式化选项。像 %Y 代表年份和 %m 代表月份这样的格式代码会创建自定义日期字符串。

区域设置会影响月份和日期的名称。该示例显示了尝试使用法语区域设置进行日期格式化。

将 struct_time 转换为时间戳

可以使用 mktime()struct_time 对象转换回时间戳。此示例演示了转换过程。

convert_to_timestamp.py
import time

# Create a struct_time for a specific date
birthday = time.strptime("1990-05-15", "%Y-%m-%d")

# Convert to timestamp
timestamp = time.mktime(birthday)
print(f"Birthday timestamp: {timestamp}")

# Convert back to verify
converted_back = time.localtime(timestamp)
print("Converted back:", converted_back)

# Compare original and converted
print("Original:", birthday.tm_year, birthday.tm_mon, birthday.tm_mday)
print("Converted:", converted_back.tm_year, converted_back.tm_mon, converted_back.tm_mday)

mktime() 将本地时间转换为自 epoch 以来的秒数。该示例显示了从字符串到 struct_time 再到时间戳以及再返回的往返转换。

请注意,mktime() 使用本地时间,而 gmtime() 将使用 UTC。夏令时可能会影响转换。

创建自定义 struct_time 对象

虽然通常由时间函数创建,但您可以创建自定义 struct_time 对象。此示例显示了手动创建。

custom_struct.py
import time

# Create a custom struct_time (9-element sequence)
custom_time = time.struct_time((2025, 12, 31, 23, 59, 59, 2, 365, 0))

print("Custom time tuple:", custom_time)
print(f"New Year's Eve {custom_time.tm_year}:")
print(time.strftime("%A, %B %d at %I:%M %p", custom_time))

# Note: Some values are calculated automatically
print("Day of week (0-6, 0 is Monday):", custom_time.tm_wday)
print("Day of year (1-366):", custom_time.tm_yday)

struct_time 构造函数采用一个包含 9 个元素的序列。该示例创建了 2025 年 12 月 31 日晚上 11:59:59 的时间元组。

某些值(如 tm_wday(星期几)和 tm_yday(一年中的第几天))会根据提供的日期组成部分自动计算。

比较 struct_time 对象

可以比较 struct_time 对象以确定时间顺序。此示例演示了比较运算。

compare_time.py
import time

def create_time(date_str):
    return time.strptime(date_str, "%Y-%m-%d")

# Create several time objects
time1 = create_time("2025-01-15")
time2 = create_time("2025-03-20")
time3 = create_time("2025-01-15")

# Comparisons
print("time1 == time3:", time1 == time3)
print("time1 < time2:", time1 < time2)
print("time2 > time3:", time2 > time3)

# Sorting a list of times
times = [
    create_time("2025-12-01"),
    create_time("2025-04-15"),
    create_time("2025-08-20")
]
sorted_times = sorted(times)
print("\nSorted times:")
for t in sorted_times:
    print(time.strftime("%Y-%m-%d", t))

struct_time 对象支持比较运算符(<、>、== 等)。这允许对日期和时间进行排序和按时间顺序比较。

该示例显示了从字符串创建多个时间对象,比较它们并对日期列表进行排序。比较是逐个字段进行的。

使用时区

struct_time 对象可以同时表示本地时间和 UTC 时间。此示例显示了使用不同时区。

timezones.py
import time

# Get current time in different representations
local_now = time.localtime()
utc_now = time.gmtime()
timestamp = time.time()

print("Local time:", time.strftime("%Y-%m-%d %H:%M:%S", local_now))
print("UTC time:", time.strftime("%Y-%m-%d %H:%M:%S", utc_now))

# Calculate time difference
local_hour = local_now.tm_hour
utc_hour = utc_now.tm_hour
time_diff = (local_hour - utc_hour) % 24
print(f"Local time is UTC+{time_diff} hours")

# Convert between local and UTC
def local_to_utc(t):
    timestamp = time.mktime(t)
    return time.gmtime(timestamp)

def utc_to_local(t):
    timestamp = time.mktime(t) - time.timezone
    return time.localtime(timestamp)

converted_utc = local_to_utc(local_now)
print("\nLocal converted to UTC:", time.strftime("%Y-%m-%d %H:%M:%S", converted_utc))

converted_local = utc_to_local(utc_now)
print("UTC converted to local:", time.strftime("%Y-%m-%d %H:%M:%S", converted_local))

此示例演示了本地时间和 UTC 时间之间的区别。它包括在两种表示形式之间进行转换的函数。

时间差计算显示了本地 UTC 偏移量(以小时为单位)。夏令时可能会影响这些转换。

最佳实践

资料来源

作者

我的名字是 Jan Bodnar,我是一位充满激情的程序员,拥有丰富的编程经验。 自 2007 年以来,我一直在撰写编程文章。迄今为止,我已经撰写了超过 1,400 篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有 Python 教程