Python epoch to Datetime

In Python, the epoch refers to the starting point for time representation. The epoch time (or Unix timestamp) is the number of seconds (or sometimes milliseconds) that have elapsed since January 1, 1970, at 00:00:00 UTC (Coordinated Universal Time).

Python provides several ways to convert an epoch timestamp into a human-readable datetime format.

1. Understanding Epoch Time

  • Epoch time, also known as POSIX time or Unix time, is the representation of time as a single number.
  • The number is monotonic, that is, always increasing, except for leap seconds adjustments.
  • Examples of epoch timestamps:
    • 01970-01-01 00:00:00 UTC
    • 1707072000 → This is a date in 2024.
    • 1924982400 → This is a future date in 2031.

2. Converting Epoch to Datetime in Python

Python has multiple libraries for dealing with timestamps. The two most common ones are:

  • datetime (for handling date and time)
  • time (for working with timestamps)

Method 1: Using datetime Module

The datetime module provides datetime.fromtimestamp() and datetime.utcfromtimestamp() to convert an epoch timestamp into a datetime object.

Example: Convert Epoch to Local Datetime

from datetime import datetime

epoch_time = 1707072000  # Example epoch timestamp
dt = datetime.fromtimestamp(epoch_time)

print("Local DateTime:", dt)

Output:

Local DateTime: 2024-02-05 00:00:00
  • This converts the epoch timestamp to the local time zone.

Example: Convert Epoch to UTC Datetime

dt_utc = datetime.utcfromtimestamp(epoch_time)
print("UTC DateTime:", dt_utc)

Output:

UTC DateTime: 2024-02-04 18:30:00
  • utcfromtimestamp() converts the epoch timestamp to UTC (Coordinated Universal Time).

Method 2: Using time Module

The time module provides time.ctime() and time.gmtime() for epoch conversion.

Example: Convert Epoch to Human-Readable Time

import time

epoch_time = 1707072000
human_time = time.ctime(epoch_time)

print("Human-Readable Time:", human_time)

Output:

Human-Readable Time: Mon Feb  5 00:00:00 2024
  • time.ctime() converts an epoch timestamp into a formatted string (local time).

Example: Convert Epoch to UTC Struct

utc_time = time.gmtime(epoch_time)
print("UTC Time Struct:", utc_time)

Output (struct_time format):

UTC Time Struct: time.struct_time(tm_year=2024, tm_mon=2, tm_mday=4, tm_hour=18, tm_min=30, tm_sec=0, tm_wday=6, tm_yday=35, tm_isdst=0)
  • time.gmtime() returns a struct_time object in UTC.

3. Formatting Datetime Objects

Once you have a datetime object, you can format it into a readable string using strftime().

Example: Convert Epoch to Custom Formatted String

formatted_time = dt.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted Time:", formatted_time)

Output:

Formatted Time: 2024-02-05 00:00:00
  • %Y → Year
  • %m → Month
  • %d → Day
  • %H → Hours
  • %M → Minutes
  • %S → Seconds

For more formatting options, refer to the Python strftime documentation.

4. Converting Milliseconds Epoch to Datetime

Sometimes, epoch timestamps are given in milliseconds (e.g., from JavaScript).

Example: Convert Milliseconds Epoch to Datetime

epoch_millis = 1707072000000  # Milliseconds timestamp
dt_millis = datetime.fromtimestamp(epoch_millis / 1000)  # Convert to seconds

print("DateTime from Milliseconds:", dt_millis)

Output:

DateTime from Milliseconds: 2024-02-05 00:00:00
  • We divide by 1000 to convert milliseconds to seconds.

5. Converting Datetime Back to Epoch

You can convert a datetime object back into an epoch timestamp using timestamp().

Example: Convert Datetime to Epoch

epoch_again = dt.timestamp()
print("Epoch Timestamp:", epoch_again)

Output:

Epoch Timestamp: 1707072000.0
  • .timestamp() returns a floating-point number.

6. Handling Timezones with pytz

The datetime module alone does not handle time zones well. For timezone-aware conversions, use the pytz library.

Example: Convert Epoch to Specific Timezone

from datetime import datetime
import pytz

epoch_time = 1707072000
timezone = pytz.timezone("Asia/Kolkata")  # Indian Standard Time (IST)
dt_timezone = datetime.fromtimestamp(epoch_time, tz=timezone)

print("DateTime in IST:", dt_timezone)

Output:

DateTime in IST: 2024-02-05 05:30:00+05:30
  • This converts the epoch timestamp to IST (UTC+5:30).

7. Using datetime with timezone from datetime module

If you don’t want to use pytz, you can use datetime.timezone (Python 3.2+).

Example: Convert to UTC Timezone

from datetime import timezone

dt_utc = datetime.fromtimestamp(epoch_time, tz=timezone.utc)
print("UTC Datetime:", dt_utc)

Output:

UTC Datetime: 2024-02-04 18:30:00+00:00
  • timezone.utc ensures the datetime object is timezone-aware.

Summary Table

MethodDescriptionExample
datetime.fromtimestamp(ts)Convert epoch to local datetimedatetime.fromtimestamp(1707072000)
datetime.utcfromtimestamp(ts)Convert epoch to UTC datetimedatetime.utcfromtimestamp(1707072000)
time.ctime(ts)Convert epoch to human-readable stringtime.ctime(1707072000)
time.gmtime(ts)Convert epoch to UTC struct_timetime.gmtime(1707072000)
datetime.strftime()Format datetime objectdt.strftime("%Y-%m-%d %H:%M:%S")
datetime.timestamp()Convert datetime to epochdt.timestamp()
datetime.fromtimestamp(ts, tz=pytz.timezone("Asia/Kolkata"))Convert epoch to specific timezonepytz.timezone("Asia/Kolkata")

Final Thoughts

  • Epoch timestamps can be used for storing and comparison of time.
  • Python offers several methods to convert between epoch and human-readable formats.
  • Timezone handling is critical in dealing with global applications.
  • Use pytz or datetime.timezone for timezone-aware datetime objects.