ZetCode

Python time.gmtime 函数

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

本综合指南探讨了 Python 的 time.gmtime 函数,该函数将自 epoch 以来的秒数转换为 UTC 时间结构。我们将介绍 UTC 时间转换、结构操作和实际示例。

基本定义

time.gmtime 函数将自 epoch 以来的秒数转换为 UTC 时间结构 (struct_time)。它以协调世界时表示时间。

主要特点:返回一个包含 9 个时间分量的命名元组,忽略时区设置,并且对于一致的 UTC 时间表示很有用。输入是自 epoch(1970 年 1 月 1 日)以来的秒数。

基本 UTC 时间转换

time.gmtime 最简单的用法是将当前时间转换为 UTC。此示例显示了基本用法和 struct_time 分量。

basic_gmtime.py
import time

# Get current timestamp
timestamp = time.time()

# Convert to UTC time struct
utc_time = time.gmtime(timestamp)

print("UTC time struct:", utc_time)
print("Year:", utc_time.tm_year)
print("Month:", utc_time.tm_mon)
print("Day:", utc_time.tm_mday)
print("Hour:", utc_time.tm_hour)
print("Minute:", utc_time.tm_min)
print("Second:", utc_time.tm_sec)

此示例演示了将当前时间转换为 UTC。struct_time 包含年、月、日、小时、分钟、秒和其他分量。

由于夏令时不适用于协调世界时,因此 UTC 时间的 tm_isdst 标志始终为 0。

转换特定时间戳

time.gmtime 可以将任何有效的 epoch 时间戳转换为 UTC。此示例显示了特定历史时间戳的转换。

specific_timestamps.py
import time

# Unix epoch (January 1, 1970)
epoch = time.gmtime(0)
print("Unix epoch:", time.strftime("%Y-%m-%d %H:%M:%S", epoch))

# First human on the moon (July 20, 1969 20:17 UTC)
moon_landing = time.gmtime(-14159000)
print("Moon landing:", time.strftime("%Y-%m-%d %H:%M:%S", moon_landing))

# Python 1.0 release (January 1994)
python_release = time.gmtime(757382400)
print("Python 1.0:", time.strftime("%Y-%m-%d", python_release))

此示例将特定的历史时刻转换为 UTC 时间结构。负值表示 Unix epoch 之前的时间戳。

strftime 函数根据指定的格式代码将时间结构格式化为可读的字符串。

比较 gmtime 和 localtime

虽然 gmtime 返回 UTC,但 localtime 返回本地时间。此示例比较了两个函数。

compare_localtime.py
import time

timestamp = time.time()

utc_time = time.gmtime(timestamp)
local_time = time.localtime(timestamp)

print("UTC time:", time.strftime("%Y-%m-%d %H:%M:%S", utc_time))
print("Local time:", time.strftime("%Y-%m-%d %H:%M:%S", local_time))
print("Timezone offset:", (local_time.tm_hour - utc_time.tm_hour), "hours")

UTC 和本地时间之间的差异取决于您的时区。该示例计算了以小时为单位的时区偏移量。

为了在系统之间获得一致的结果,UTC (gmtime) 优于本地时间,后者因时区设置而异。

使用时间结构组件

gmtime 返回的时间结构具有可访问的属性。此示例演示了使用单个组件。

struct_components.py
import time

utc_time = time.gmtime()

# Accessing struct components
print("Current UTC time components:")
print(f"Year: {utc_time.tm_year}")
print(f"Month: {utc_time.tm_mon} ({time.strftime('%B', utc_time)})")
print(f"Day of month: {utc_time.tm_mday}")
print(f"Day of week: {utc_time.tm_wday} ({time.strftime('%A', utc_time)})")
print(f"Day of year: {utc_time.tm_yday}")
print(f"Hour: {utc_time.tm_hour}")
print(f"Minute: {utc_time.tm_min}")
print(f"Second: {utc_time.tm_sec}")
print(f"DST flag: {utc_time.tm_isdst} (always 0 for UTC)")

struct_time 是一个具有可读属性的命名元组。工作日为 0-6(星期一至星期日),月份为 1-12,DST 标志对于 UTC 始终为 0。

strftime 函数可以将数字组件转换为可读的名称(如月份名称)。

创建自定义 UTC 时间

您可以通过转换特定的时间戳来创建自定义 UTC 时间。此示例显示了为特定日期创建时间。

custom_times.py
import time

def create_utc_time(year, month, day, hour=0, minute=0, second=0):
    """Create a UTC time struct for specific date/time"""
    time_str = f"{year}-{month:02d}-{day:02d} {hour:02d}:{minute:02d}:{second:02d}"
    time_tuple = (year, month, day, hour, minute, second, 0, 0, 0)
    timestamp = time.mktime(time_tuple) - time.timezone
    return time.gmtime(timestamp)

# Create specific UTC times
new_year = create_utc_time(2025, 1, 1, 0, 0, 0)
print("New Year 2025:", time.strftime("%Y-%m-%d %H:%M:%S", new_year))

eclipse = create_utc_time(2024, 4, 8, 18, 18, 0)
print("Solar eclipse 2024:", time.strftime("%Y-%m-%d %H:%M:%S", eclipse))

此示例为特定日期和时间创建 UTC 时间结构。该函数在创建时间戳时会考虑时区偏移量。

请注意,此方法适用于 1970 年之后的日期。对于历史日期,请考虑改用 datetime 模块。

在时间格式之间转换

time.gmtime 有助于在不同的时间格式之间进行转换。此示例显示了时间戳、结构和字符串之间的转换。

time_conversions.py
import time

# Current timestamp
timestamp = time.time()

# Convert to UTC struct
utc_struct = time.gmtime(timestamp)

# Convert struct to formatted string
time_str = time.strftime("%Y-%m-%d %H:%M:%S", utc_struct)

# Convert string back to struct
parsed_struct = time.strptime(time_str, "%Y-%m-%d %H:%M:%S")

# Convert struct back to timestamp
new_timestamp = time.mktime(parsed_struct) - time.timezone

print("Original timestamp:", timestamp)
print("Formatted string:", time_str)
print("Reconstructed timestamp:", new_timestamp)
print("Difference:", abs(timestamp - new_timestamp), "seconds")

这演示了不同时间表示形式之间的完整转换周期。细微的差异来自浮点精度。

strptime 函数将字符串解析为时间结构,而 strftime 将结构格式化为字符串。

使用 gmtime 进行时区转换

当与偏移量结合使用时,time.gmtime 可以帮助进行时区转换。此示例将 UTC 转换为不同的时区。

timezone_conversion.py
import time

def utc_to_timezone(utc_struct, offset_hours):
    """Convert UTC struct_time to another timezone"""
    timestamp = time.mktime(utc_struct) - time.timezone
    adjusted_timestamp = timestamp + (offset_hours * 3600)
    return time.gmtime(adjusted_timestamp)

current_utc = time.gmtime()

# Convert to different timezones
print("UTC:", time.strftime("%Y-%m-%d %H:%M", current_utc))
print("New York (EST):", time.strftime("%Y-%m-%d %H:%M", 
      utc_to_timezone(current_utc, -5)))
print("Tokyo (JST):", time.strftime("%Y-%m-%d %H:%M", 
      utc_to_timezone(current_utc, 9)))
print("London (GMT):", time.strftime("%Y-%m-%d %H:%M", 
      utc_to_timezone(current_utc, 0)))

此示例通过应用小时偏移量将 UTC 时间转换为不同的时区。请注意,这不考虑夏令时变化。

对于生产代码,请考虑使用 pytzzoneinfo 模块以获得更强大的时区处理。

最佳实践

资料来源

作者

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

列出所有 Python 教程