杰瑞科技汇

Python字符串时间戳如何转换或处理?

Of course! In Python, converting a timestamp to a string is a very common task. The key is to use the datetime module, which is Python's standard library for handling dates and times.

Python字符串时间戳如何转换或处理?-图1
(图片来源网络,侵删)

The process generally involves two steps:

  1. Get a timestamp: This is usually a number representing seconds since the "Epoch" (January 1, 1970).
  2. Convert the timestamp to a datetime object: This object makes it easy to format the date and time exactly how you want.
  3. Format the datetime object into a string: Use the strftime() method to create your desired string format.

The Core Method: datetime.fromtimestamp()

The most straightforward way is to use datetime.fromtimestamp().

Here is a complete, step-by-step example.

Step 1: Import the datetime module

from datetime import datetime

Step 2: Get a timestamp (for demonstration)

If you don't have a timestamp, you can get the current one using time.time(). We'll use this for our example.

Python字符串时间戳如何转换或处理?-图2
(图片来源网络,侵删)
import time
# Get the current timestamp (a floating-point number)
current_timestamp = time.time()
print(f"Original Timestamp: {current_timestamp}")
# Example Output: Original Timestamp: 1678886400.123456

Step 3: Convert the timestamp to a datetime object

Use datetime.fromtimestamp() to create a datetime object. This object is now "aware" of the date and time.

# Convert the timestamp to a datetime object
# By default, this uses the local timezone of your system.
dt_object = datetime.fromtimestamp(current_timestamp)
print(f"Datetime Object: {dt_object}")
# Example Output: Datetime Object: 2025-03-15 14:26:40.123456

Step 4: Format the datetime object into a string

This is the final step. Use the strftime() method (which stands for "string format time") on your datetime object.

You use special format codes (like %Y, %m, %d) to define the output string.

Code Meaning Example
%Y Year with century 2025
%y Year without century 23
%m Month as a zero-padded number 03
%B Full month name March
%b Abbreviated month name Mar
%d Day of the month 15
%A Full weekday name Wednesday
%a Abbreviated weekday name Wed
%H Hour (24-hour clock) 14
%I Hour (12-hour clock) 02
%M Minute 26
%S Second 40
%p AM/PM designation PM
%f Microsecond 123456
%Z Timezone name CST
%z UTC offset +0600

Example Formatted Strings:

Python字符串时间戳如何转换或处理?-图3
(图片来源网络,侵删)
# Example 1: Standard format (ISO 8601)
iso_string = dt_object.strftime("%Y-%m-%dT%H:%M:%S")
print(f"ISO 8601 String: {iso_string}")
# Example Output: ISO 8601 String: 2025-03-15T14:26:40
# Example 2: Readable format
readable_string = dt_object.strftime("%A, %B %d, %Y at %I:%M %p")
print(f"Readable String: {readable_string}")
# Example Output: Readable String: Wednesday, March 15, 2025 at 02:26 PM
# Example 3: Numeric format
numeric_string = dt_object.strftime("%m/%d/%y %H:%M")
print(f"Numeric String: {numeric_string}")
# Example Output: Numeric String: 03/15/23 14:26

Handling Timezones (Important!)

The examples above use your system's local timezone. For applications, it's often better to be explicit about the timezone, especially when dealing with servers or different users.

The modern, recommended way to handle timezones is with the zoneinfo module (available in Python 3.9+).

Example: Converting to UTC

from datetime import datetime, timezone
import time
# Get current timestamp
timestamp = time.time()
# Convert to a UTC datetime object
# .fromtimestamp() can take a timezone as a second argument
dt_object_utc = datetime.fromtimestamp(timestamp, tz=timezone.utc)
# Format the UTC time
utc_string = dt_object_utc.strftime("%Y-%m-%d %H:%M:%S %Z")
print(f"UTC String: {utc_string}")
# Example Output: UTC String: 2025-03-15 09:26:40 UTC

Example: Converting to a Specific Timezone (e.g., New York)

from datetime import datetime, timezone
import time
from zoneinfo import ZoneInfo # Requires Python 3.9+
timestamp = time.time()
# Define the timezone you want to convert to
tz_ny = ZoneInfo("America/New_York")
# Convert the timestamp to a datetime object in the NY timezone
dt_object_ny = datetime.fromtimestamp(timestamp, tz=tz_ny)
# Format the New York time
ny_string = dt_object_ny.strftime("%Y-%m-%d %H:%M:%S %Z")
print(f"New York String: {ny_string}")
# Example Output: New York String: 2025-03-15 05:26:40 EDT

Note: If you are on Python 3.8 or earlier, you would use the pytz library instead of zoneinfo. The usage is very similar.


Complete, Runnable Example

Here is a full script you can run to see all the concepts in action.

import time
from datetime import datetime, timezone
from zoneinfo import ZoneInfo # Requires Python 3.9+
def convert_timestamp_to_string(timestamp, timezone_str=None):
    """
    Converts a Unix timestamp to a formatted string.
    Args:
        timestamp (float): The Unix timestamp (seconds since epoch).
        timezone_str (str, optional): The timezone to format the string in
                                      (e.g., "UTC", "America/New_York").
                                      Defaults to local system timezone.
    """
    if timezone_str:
        tz = ZoneInfo(timezone_str)
        dt_object = datetime.fromtimestamp(timestamp, tz=tz)
    else:
        # Use local timezone if no timezone is specified
        dt_object = datetime.fromtimestamp(timestamp)
    # Define some common format strings
    formats = {
        "ISO 8601": "%Y-%m-%dT%H:%M:%S%z",
        "Readable US": "%A, %B %d, %Y at %I:%M:%S %p",
        "Log Format": "%Y-%m-%d %H:%M:%S",
        "Numeric": "%m/%d/%y %H:%M:%S",
        "Short Date": "%x",
        "Short Time": "%X"
    }
    print(f"\n--- For Timestamp: {timestamp} ---")
    if timezone_str:
        print(f"--- Timezone: {timezone_str} ---")
    else:
        print(f"--- Timezone: Local System ({dt_object.tzinfo}) ---")
    for name, fmt_str in formats.items():
        formatted_string = dt_object.strftime(fmt_str)
        print(f"{name:15}: {formatted_string}")
# --- Main execution ---
if __name__ == "__main__":
    # Get a current timestamp to use
    current_time = time.time()
    # Example 1: Using the local system timezone
    convert_timestamp_to_string(current_time)
    # Example 2: Explicitly converting to UTC
    convert_timestamp_to_string(current_time, "UTC")
    # Example 3: Converting to a specific timezone (e.g., London)
    convert_timestamp_to_string(current_time, "Europe/London")

Summary

Goal Method
Convert a timestamp to a datetime object datetime.fromtimestamp(your_timestamp)
Convert a datetime object to a string your_datetime_object.strftime("your_format_string")
Handle timezones Use datetime.fromtimestamp(ts, tz=ZoneInfo("...")) (Python 3.9+)
Get the current timestamp import time; time.time()
分享:
扫描分享到社交APP
上一篇
下一篇