杰瑞科技汇

python fromtimestamp

Of course! The fromtimestamp() method is a fundamental part of Python's datetime module. It's used to convert a timestamp (a number representing seconds since the "Epoch") into a human-readable datetime object.

python fromtimestamp-图1
(图片来源网络,侵删)

Here’s a complete guide covering what it is, how to use it, and important details.

What is a Timestamp?

A timestamp is a numerical value that represents a specific point in time. In most modern systems (like Unix, Linux, and macOS), this value is the number of seconds that have elapsed since January 1, 1970, at 00:00:00 UTC. This date is known as the Epoch.

  • Example: 1672531200 is a timestamp. It represents January 1, 2025, at 00:00:00 UTC.

The fromtimestamp() Method

This method is a class method of the datetime class. It takes a timestamp (as a float or int) and returns a datetime object corresponding to that timestamp in the local timezone of the system where the code is running.

Basic Syntax

from datetime import datetime
# The most common usage
datetime_object = datetime.fromtimestamp(timestamp)

Key Parameters

  1. timestamp (required): This is the number you want to convert. It can be an integer or a float.
    • Integer: Represents whole seconds.
    • Float: Represents seconds with fractional parts (milliseconds, microseconds).
  2. tz (optional): A timezone object from the zoneinfo module (Python 3.9+) or pytz library. If you don't provide this, the method uses your system's local timezone. This is a crucial parameter for writing timezone-aware code.

Examples

Let's walk through some common use cases.

python fromtimestamp-图2
(图片来源网络,侵删)

Example 1: Basic Conversion

Convert a simple integer timestamp to a datetime object.

from datetime import datetime
# A timestamp for January 1, 2025, 00:00:00 UTC
timestamp = 1672531200
# Convert the timestamp to a datetime object
dt_object = datetime.fromtimestamp(timestamp)
print(f"Timestamp: {timestamp}")
print(f"Datetime Object: {dt_object}")
print(f"Type of object: {type(dt_object)}")

Output (will vary based on your local timezone):

Timestamp: 1672531200
Datetime Object: 2025-01-01 01:00:00  <-- Note the time is adjusted to my local timezone (CET/CEST)
Type of object: <class 'datetime.datetime'>

Notice how the time is 01:00:00 instead of 00:00:00. This is because my computer's local timezone is set to Europe/Stockholm, which was at UTC+1 at that time.

Example 2: Handling Fractional Seconds (Milliseconds)

Timestamps are often floats. The fractional part represents the time with more precision.

python fromtimestamp-图3
(图片来源网络,侵删)
from datetime import datetime
# A timestamp with milliseconds for January 1, 2025, 00:00:30.500 UTC
timestamp = 1672531230.5
dt_object = datetime.fromtimestamp(timestamp)
print(f"Timestamp: {timestamp}")
print(f"Datetime Object: {dt_object}")
print(f"Microsecond part: {dt_object.microsecond}")

Output (again, timezone-adjusted):

Timestamp: 1672531230.5
Datetime Object: 2025-01-01 01:00:30.500000
Microsecond part: 500000

The 5 seconds were correctly converted to 500000 microseconds.

Example 3: Using the tz Parameter (Timezone-Aware Conversion)

This is the recommended way to handle timezones in modern Python (3.9+). It ensures your code behaves predictably on any machine, regardless of its system timezone settings.

First, you need to import the ZoneInfo class.

from datetime import datetime
from zoneinfo import ZoneInfo # Requires Python 3.9+
# The same timestamp as before
timestamp = 1672531200
# --- Convert to UTC explicitly ---
# Create a timezone object for UTC
utc_timezone = ZoneInfo("UTC")
# Use the 'tz' parameter to create a timezone-aware datetime object
dt_utc = datetime.fromtimestamp(timestamp, tz=utc_timezone)
print(f"Timestamp: {timestamp}")
print(f"UTC Datetime Object: {dt_utc}")
print(f"Timezone Info: {dt_utc.tzinfo}")
# --- Convert to a different timezone (e.g., 'America/New_York') ---
ny_timezone = ZoneInfo("America/New_York")
dt_ny = datetime.fromtimestamp(timestamp, tz=ny_timezone)
print("\n--- New York Time ---")
print(f"New York Datetime Object: {dt_ny}")
print(f"Timezone Info: {dt_ny.tzinfo}")

Output:

Timestamp: 1672531200
UTC Datetime Object: 2025-01-01 00:00:00+00:00
Timezone Info: UTC
--- New York Time ---
New York Datetime Object: 2025-12-31 19:00:00-05:00
Timezone Info: America/New_York

As you can see, the same timestamp results in different local times depending on the target timezone. This is the correct and robust way to handle time.


Important Considerations and "Gotchas"

fromtimestamp() vs utcfromtimestamp()

Method Behavior Use Case
fromtimestamp() Converts a timestamp to a local datetime object. When you want to display a time in the user's or server's local timezone.
utcfromtimestamp() Converts a timestamp to a naive UTC datetime object. When you need to work with time in a standardized, timezone-agnostic way.

Example:

from datetime import datetime
timestamp = 1672531200
# Local time (system-dependent)
local_dt = datetime.fromtimestamp(timestamp)
# UTC time (consistent)
utc_dt = datetime.utcfromtimestamp(timestamp)
print(f"Local Datetime: {local_dt}")
print(f"UTC Datetime:   {utc_dt}")

Output:

Local Datetime: 2025-01-01 01:00:00  <-- My local time (CET/CEST)
UTC Datetime:   2025-01-01 00:00:00  <-- The actual UTC time

Handling the "Epoch"

What happens if you pass a timestamp for before 1970 (a negative number)?

from datetime import datetime
# Timestamp for January 1, 1969, 00:00:00 UTC
timestamp = -31536000
dt_object = datetime.fromtimestamp(timestamp)
print(dt_object)

Output:

1968-12-31 23:00:00  <-- Adjusted for my local timezone (CET/CEST)

The function handles negative timestamps correctly.

What if the Timestamp is Invalid?

If you provide a timestamp that is out of the valid range for the platform's C localtime() or gmtime() functions, Python will raise an OSError.

# This will likely raise an OSError on most systems
# datetime.MINYEAR is 1, and datetime.MAXYEAR is 9999.
# The valid range of timestamps is system-dependent.
try:
    datetime.fromtimestamp(-100000000000)
except OSError as e:
    print(f"Error: {e}")

Summary

Task Method to Use Example
Convert timestamp to local time datetime.fromtimestamp(ts) dt = datetime.fromtimestamp(1672531200)
Convert timestamp to UTC datetime.utcfromtimestamp(ts) dt = datetime.utcfromtimestamp(1672531200)
Convert timestamp to a specific timezone datetime.fromtimestamp(ts, tz=ZoneInfo(...)) dt = datetime.fromtimestamp(1672531200, tz=ZoneInfo("Asia/Tokyo"))
分享:
扫描分享到社交APP
上一篇
下一篇