Python datetime fromtimestamp() Method

Usage

The fromtimestamp() method is part of the datetime module in Python. Its primary function is to convert a POSIX timestamp (also known as Unix timestamp) into a Python datetime object.

What is a Unix Timestamp?

A Unix timestamp is a numerical representation of the number of seconds that have passed since the Unix Epoch, which is January 1st, 1970 at 00:00:00 UTC (Coordinated Universal Time). Think of it as a continuous count of seconds from this specific reference point in time.

The advantage of Unix timestamps is that they offer a standardized, unambiguous way to represent a moment in time, regardless of your location on Earth. This makes them extremely useful for computer systems that need to track and organize dated information in dynamic and distributed applications, both online and on the client side.

Syntax

datetime.fromtimestamp(timestamp, tz=None)

Parameters

ParameterConditionDescription
timestampRequiredA Unix timestamp you want to convert.
tzOptionalSpecifies the timezone of the resulting datetime object.
Default is None.

Return Value

The method returns a datetime object corresponding to the given Unix timestamp.

If optional argument tz is provided (and is not None), the resulting datetime object becomes “aware” and carries the specified time zone information. Otherwise, the datetime object will be “naive” (it does not contain timezone information) and is considered to be in the local timezone.

It’s important to understand that the fromtimestamp() function does not consider leap seconds. A leap seconds are extra seconds added to Coordinated Universal Time (UTC) to keep up with the Earth’s rotation.

On non-POSIX systems that internally include leap seconds in their notion of a timestamp, leap seconds are ignored by fromtimestamp(). So, you might find that even if two timestamps are a second apart, they could end up giving you the same datetime objects.

Module Import

To use the fromtimestamp() method, you need to import the datetime module first.

from datetime import datetime

Naive vs. Aware datetime Objects

Python’s datetime objects can be classified into two categories: naive and aware.

  • Naive: A naive datetime object doesn’t include any information about time zones. This can lead to ambiguities if you handle dates and times across different time zones.
  • Aware: An aware datetime object explicitly carries time zone information, meaning it knows its offset from UTC. This makes operations involving different time zones much safer and prevents misinterpretations.

Basic Conversion to datetime

The most straightforward use of the fromtimestamp() function is to convert a Unix timestamp into a Python datetime object. Let’s see an example:

from datetime import datetime

# Example Unix timestamp
timestamp = 1683038400
datetime_obj = datetime.fromtimestamp(timestamp)
print("Datetime:", datetime_obj)
# Datetime: 2023-05-02 20:10:00

If you check the tzinfo attribute of the datetime_obj, you’ll see that it’s None.

print(datetime_obj.tzinfo)
# Output: None

This indicates that the resulting datetime object is “naive,” meaning it has no associated time zone information. By default, fromtimestamp() assumes the timestamp represents a time in your system’s local time zone.

Converting to Aware datetime with UTC

To create a timezone-aware datetime object, you need to provide a timezone object to the tz argument of the fromtimestamp() function.

If your timestamp represents a time in Coordinated Universal Time (UTC), you can directly use the datetime.timezone.utc attribute as the tz argument. Let’s illustrate this with an example:

from datetime import datetime, timezone

# Example Unix timestamp
timestamp = 1683038400

datetime_obj = datetime.fromtimestamp(timestamp, timezone.utc)
print("UTC datetime:", datetime_obj)
# UTC datetime: 2023-05-02 14:40:00+00:00

By checking the tzinfo attribute, you can confirm that the resulting datetime_obj is now aware of its time zone (UTC).

print(datetime_obj.tzinfo)
# Output: UTC

Localizing a Timestamp to a Specific Timezone with zoneinfo

If you’re working with time zones other than UTC, the zoneinfo module (available in Python 3.9 and later) can be very helpful. Let’s see how to use it to convert a timestamp into a datetime object representing Eastern Standard Time (EST):

from datetime import datetime
from zoneinfo import ZoneInfo

# Specify the timezone
timezone = ZoneInfo('US/Eastern')

# Example Unix timestamp
timestamp = 1683038400

datetime_obj = datetime.fromtimestamp(timestamp, timezone)
print("EST datetime:", datetime_obj)
# EST datetime: 2023-05-02 10:40:00-04:00

print(datetime_obj.tzinfo)
# Output: US/Eastern

Handling Fractional Seconds

Unix timestamps can include fractional parts to represent milliseconds and microseconds. fromtimestamp() can handle these fractional seconds accurately. Let’s see this in action:

from datetime import datetime

# Timestamp with fractional seconds
timestamp = 1683038400.123456

datetime_obj = datetime.fromtimestamp(timestamp)
print("Datetime with microseconds:", datetime_obj)
# Datetime with microseconds: 2023-05-02 20:10:00.123456

Note that if the timestamp has higher precision beyond microseconds, the datetime object will store and display only up to the microsecond level.