杰瑞科技汇

Python structtime如何转换为时间戳?

Of course! Let's dive deep into Python's time.struct_time object. It's a fundamental concept for working with dates and times, especially when interacting with low-level system functions.

Python structtime如何转换为时间戳?-图1
(图片来源网络,侵删)

What is struct_time?

struct_time is a named tuple that acts as a convenient container for holding a broken-down time value. "Broken-down" means the time is represented by its individual components (year, month, day, hour, etc.) rather than a single number (like a Unix timestamp).

Think of it like a C struct for time, hence the name.


Key Characteristics

  1. It's a Named Tuple: This is its most important feature. You can access its values in two ways:

    • By index (e.g., tm[0]), which is not recommended as it's not readable.
    • By attribute name (e.g., tm_year), which is highly readable and preferred.
  2. It's Immutable: You cannot change the value of a struct_time object after it has been created. If you need to modify it, you must create a new one.

    Python structtime如何转换为时间戳?-图2
    (图片来源网络,侵删)
  3. It Has Two Flavors: struct_time objects can be "time zone naive" or "time zone aware".

    • naive: This is the most common type. It contains no information about the time zone (like UTC or EST). It's just a set of numbers.
    • aware: This type includes a tm_zone attribute (time zone name, e.g., "EST") and a tm_gmtoff attribute (offset from UTC in seconds). This is less common and primarily used on Unix-like systems.

Creating a struct_time Object

You will almost never create a struct_time object directly using the constructor (time.struct_time(...)). Instead, you get them as return values from functions in Python's built-in time module.

From a Unix Timestamp (Most Common)

The time.localtime() and time.gmtime() functions convert a Unix timestamp (seconds since the Epoch, 1970-01-01 00:00:00 UTC) into a struct_time.

  • time.localtime(): Converts to the local computer's time zone.
  • time.gmtime(): Converts to UTC (Coordinated Universal Time).
import time
# Get the current time as a Unix timestamp
current_timestamp = time.time()
print(f"Current Unix Timestamp: {current_timestamp}\n")
# Convert the timestamp to a local struct_time
local_time_struct = time.localtime(current_timestamp)
print("Local Time (struct_time):")
print(local_time_struct)
print(f"Type: {type(local_time_struct)}\n")
# Convert the timestamp to a UTC struct_time
utc_time_struct = time.gmtime(current_timestamp)
print("UTC Time (struct_time):")
print(utc_time_struct)
print(f"Type: {type(utc_time_struct)}")

From a String (time.strptime)

The time.strptime() function (string parse time) parses a string into a struct_time based on a format code.

Python structtime如何转换为时间戳?-图3
(图片来源网络,侵删)
import time
# Define a time string and its format
time_string = "2025-10-27 15:30:00"
format_code = "%Y-%m-%d %H:%M:%S"
# Parse the string into a struct_time
parsed_time_struct = time.strptime(time_string, format_code)
print("Parsed Time (struct_time):")
print(parsed_time_struct)
print(f"Year: {parsed_time_struct.tm_year}")
print(f"Month: {parsed_time_struct.tm_mon}")
print(f"Hour (24-hour): {parsed_time_struct.tm_hour}")

Accessing Values in a struct_time

As mentioned, the best way is to use the attribute names. Here is a list of the available attributes:

Index Attribute Value Example (for "2025-10-27 15:30:00")
0 tm_year Year (e.g., 2025) 2025
1 tm_mon Month (1-12) 10
2 tm_mday Day of the month (1-31) 27
3 tm_hour Hour (0-23) 15
4 tm_min Minute (0-59) 30
5 tm_sec Second (0-61, 60 & 61 are leap seconds) 0
6 tm_wday Day of the week (0-6, 0 is Monday) 4
7 tm_yday Day of the year (1-366) 300
8 tm_isdst Daylight Savings Time flag (-1, 0, 1) 0 (not in effect)
-1 tm_zone Time zone name (if aware) (empty for naive structs)
-2 tm_gmtoff Offset from UTC in seconds (if aware) (empty for naive structs)
import time
# Use the struct_time from the previous example
time_struct = time.localtime()
print("--- Accessing struct_time Attributes ---")
print(f"Full object: {time_struct}")
print(f"Year (tm_year): {time_struct.tm_year}")
print(f"Month (tm_mon): {time_struct.tm_mon}")
print(f"Day of the week (tm_wday), where 0 is Monday: {time_struct.tm_wday}")
print(f"Is Daylight Saving Time? (tm_isdst): {time_struct.tm_isdst}")

Converting a struct_time Back to Other Formats

Often, you'll need to convert your struct_time object into a more usable format, like a string or a timestamp.

To a String (time.strftime)

time.strftime() (string format time) is the reverse of strptime. It formats a struct_time into a string.

import time
current_time_struct = time.localtime()
# Format the struct_time into a string
formatted_string_1 = time.strftime("%A, %B %d, %Y", current_time_struct)
formatted_string_2 = time.strftime("%H:%M:%S", current_time_struct)
print("--- Formatting struct_time to String ---")
print(f"Formatted Date: {formatted_string_1}")
print(f"Formatted Time: {formatted_string_2}")

To a Unix Timestamp (time.mktime)

time.mktime() converts a local struct_time back into a Unix timestamp. Note: This function expects a local time, not a UTC one.

import time
# Create a struct_time for a specific moment (e.g., New Year's 2025)
# Note: tm_isdst=-1 tells mktime to determine if DST is in effect automatically.
ny_eve_struct = time.struct_time((2025, 1, 1, 0, 0, 0, 0, 1, -1))
# Convert it back to a timestamp
timestamp_from_struct = time.mktime(ny_eve_struct)
print("--- Converting struct_time to Timestamp ---")
print(f"struct_time for NYE: {ny_eve_struct}")
print(f"Resulting Timestamp: {timestamp_from_struct}")

Complete Example: A Simple Log Parser

This example shows the practical use of struct_time: parsing a log file to find entries from a specific time range.

import time
# Sample log data (each line is a timestamp and a message)
log_data = [
    "1698387000 INFO: System started",
    "1698387600 ERROR: Disk full",
    "1698388200 WARNING: High memory usage",
    "1698388800 INFO: System shutdown"
]
def parse_logs(logs, start_time_str, end_time_str):
    """
    Parses logs and returns entries within a given time range.
    """
    # 1. Convert the time range strings to struct_time objects
    start_struct = time.strptime(start_time_str, "%Y-%m-%d %H:%M:%S")
    end_struct = time.strptime(end_time_str, "%Y-%m-%d %H:%M:%S")
    # 2. Convert the time range struct_time objects to timestamps for comparison
    start_timestamp = time.mktime(start_struct)
    end_timestamp = time.mktime(end_struct)
    relevant_logs = []
    print(f"--- Searching for logs between {start_time_str} and {end_time_str} ---")
    for log_entry in logs:
        # 3. Extract the timestamp from the log entry
        log_timestamp_str = log_entry.split()[0]
        log_timestamp = int(log_timestamp_str)
        # 4. Check if the log's timestamp is within our range
        if start_timestamp <= log_timestamp <= end_timestamp:
            # 5. Convert the log's timestamp to a readable struct_time for the output
            log_time_struct = time.localtime(log_timestamp)
            formatted_log_time = time.strftime("%Y-%m-%d %H:%M:%S", log_time_struct)
            message = " ".join(log_entry.split()[1:])
            relevant_logs.append(f"{formatted_log_time} - {message}")
    return relevant_logs
# Define the time range we are interested in
start_range = "2025-10-27 15:00:00"
end_range = "2025-10-27 16:00:00"
# Run the parser
filtered_logs = parse_logs(log_data, start_range, end_range)
# Print the results
for log in filtered_logs:
    print(log)

When to Use struct_time vs. datetime

While struct_time is useful, Python's datetime module is generally preferred for modern applications.

Feature time.struct_time datetime.datetime
Primary Use Low-level OS interaction, parsing/formatting with C-style codes. High-level date and time arithmetic, object-oriented programming.
Time Zones No built-in support for time zones (naive by default). Excellent support for time zones via pytz and the standard zoneinfo (Python 3.9+).
Arithmetic No built-in support. You must convert to timestamps and back. Excellent support. You can add/subtract timedelta objects easily.
Immutability Immutable. Immutable.
Readability Attribute access is good (.tm_year). Attribute access is excellent (.year, .month).

Conclusion: Use struct_time when you need to interface with system functions or libraries that require it (like some C APIs or specific file formats). For almost all other date and time manipulation in Python, prefer the datetime module.

分享:
扫描分享到社交APP
上一篇
下一篇