ZetCode

Python time.localtime 函数

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

本综合指南探讨了 Python 的 time.localtime 函数,该函数将自 epoch 以来的秒数转换为本地时间结构。我们将介绍时间结构、格式化、时区处理和实际示例。

基本定义

time.localtime 函数将自 epoch 以来的秒数转换为本地时间的时间结构。它返回一个具有时间组件的命名元组。

主要特征:考虑时区和夏令时,返回 struct_time 对象,并且是 time.mktime 的逆函数。该函数接受一个可选的秒数参数。

基本时间结构转换

time.localtime 最简单的用法是将当前时间转换为本地时间结构。此示例显示了基本用法和结构属性。

basic_localtime.py
import time

# Get current local time
local_time = time.localtime()
print("Local time struct:", local_time)

# Access struct components
print(f"Year: {local_time.tm_year}")
print(f"Month: {local_time.tm_mon}")
print(f"Day: {local_time.tm_mday}")
print(f"Hour: {local_time.tm_hour}")
print(f"Minute: {local_time.tm_min}")
print(f"Second: {local_time.tm_sec}")

此示例演示如何获取当前本地时间作为结构并访问其组件。该结构包含年、月、日等。

tm_isdst 标志指示夏令时(DST 为 1,非 DST 为 0,未知为 -1)。

将时间戳转换为本地时间

time.localtime 可以将特定的时间戳转换为本地时间。此示例显示了固定时间戳的转换。

timestamp_conversion.py
import time

# Unix epoch timestamp (January 1, 1970)
epoch_time = 0
epoch_local = time.localtime(epoch_time)
print("Epoch in local time:", epoch_local)

# Specific timestamp (July 20, 1969 moon landing)
moon_landing = -14159025
moon_local = time.localtime(moon_landing)
print("Moon landing in local time:", moon_local)

# Format the output
formatted = time.strftime("%B %d, %Y at %I:%M %p", moon_local)
print("Formatted moon landing:", formatted)

这显示了如何将历史中的特定时刻转换为本地时间。负时间戳表示 Unix epoch 之前的日期。

strftime 函数将结构格式化为可读的字符串。像 %B (月份名称) 这样的格式代码使输出更具表现力。

比较 localtime 和 gmtime

虽然 localtime 转换为本地时间,但 gmtime 转换为 UTC 时间。此示例比较了这两个函数。

localtime_vs_gmtime.py
import time

# Get current timestamp
now = time.time()

# Convert to local and UTC time
local = time.localtime(now)
utc = time.gmtime(now)

print("Local time struct:", local)
print("UTC time struct:", utc)

# Calculate timezone offset
hour_diff = local.tm_hour - utc.tm_hour
print(f"Timezone offset: {hour_diff} hours")

本地时间和 UTC 时间之间的差异显示了您的时区偏移量。这因地点和夏令时状态而异。

请注意,当您的时区不是 UTC±0 时,这些结构除了小时分量之外都是相同的。

使用时间结构组件

时间结构允许轻松访问日期组件。此示例显示了结构组件的实际用途。

struct_components.py
import time

def is_weekend():
    local = time.localtime()
    # tm_wday ranges from 0 (Monday) to 6 (Sunday)
    return local.tm_wday >= 5

def season():
    local = time.localtime()
    month = local.tm_mon
    if month in (12, 1, 2):
        return "Winter"
    elif month in (3, 4, 5):
        return "Spring"
    elif month in (6, 7, 8):
        return "Summer"
    else:
        return "Autumn"

print("Is it weekend?", is_weekend())
print("Current season:", season())

tm_wday 属性给出星期几(0-6),tm_mon 给出月份(1-12)。这些可以在不解析字符串的情况下启用基于日期的逻辑。

当您需要特定的日期组件时,这种方法比字符串解析更有效。

夏令时处理

time.localtime 自动处理夏令时。此示例演示了 DST 检测和调整。

daylight_saving.py
import time

def check_dst():
    local = time.localtime()
    if local.tm_isdst == 1:
        return "Daylight Saving Time is in effect"
    elif local.tm_isdst == 0:
        return "Standard Time is in effect"
    else:
        return "DST status unknown"

# Test around DST transition (example for US/Eastern)
dst_start = time.mktime((2025, 3, 9, 2, 0, 0, 0, 0, -1))
dst_end = time.mktime((2025, 11, 2, 2, 0, 0, 0, 0, -1))

print("Current DST status:", check_dst())
print("March 9, 2025 2:00 AM:", time.localtime(dst_start))
print("November 2, 2025 2:00 AM:", time.localtime(dst_end))

tm_isdst 标志指示 DST 状态。当设置为 -1 时,该函数会自动确定 DST 状态。

请注意,DST 转换规则因时区而异。该示例显示了 2025 年美国/东部的转换点。

创建自定义日期字符串

时间结构可以实现灵活的日期格式设置。此示例显示了从本地时间创建自定义字符串。

custom_formatting.py
import time

def friendly_date():
    local = time.localtime()
    weekday = ["Monday", "Tuesday", "Wednesday", 
               "Thursday", "Friday", "Saturday", "Sunday"][local.tm_wday]
    month = ["January", "February", "March", "April", "May", "June",
             "July", "August", "September", "October", "November", 
             "December"][local.tm_mon - 1]
    
    suffix = "th"
    if 4 <= local.tm_mday <= 20 or 24 <= local.tm_mday <= 30:
        suffix = "th"
    else:
        suffix = ["st", "nd", "rd"][local.tm_mday % 10 - 1]
    
    return f"{weekday}, {month} {local.tm_mday}{suffix}, {local.tm_year}"

print("Today is:", friendly_date())

这创建了一个人类友好的日期字符串,例如“2025 年 4 月 11 日星期二”。它处理日期的适当序数后缀(st、nd、rd、th)。

该示例演示了当 strftime 未能提供所需的灵活性时,如何进行手动格式设置。

最佳实践

资料来源

作者

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

列出所有 Python 教程