Open In App

Convert Python datetime to epoch

Last Updated : 13 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Epoch time is a way to represent time as the number of seconds that have passed since January 1, 1970, 00:00:00 UTC. It is also known as Unix time or POSIX time and it serves as a universal point of reference for representing dates and times. Its used in various applications like file timestamps, database records and logs providing consistency when working with dates and times across different systems. In this article we will learn how to convert datetime frame in epochs using python.

Method 1: Using datetime.timestamp()

  • Import the datetime Module: First import the datetime class from the datetime module.
  • Create a datetime Object: You need to create a datetime object representing the date and time you wish to convert.
  • Convert to Epoch: Use the timestamp() method on the datetime object. This method returns the number of seconds since the Unix epoch as a floating-point number.
Python
from datetime import datetime
dt = datetime(2023, 12, 3, 15, 0)

epoch_time = dt.timestamp()
print(epoch_time)

Output:

1701615600.0

This method returns a floating-point number which accounts for fractional seconds as well.

Method 2: Using calendar.timegm()

The calendar module can also be used to convert a datetime object to epoch time using the timegm() function which directly works with UTC time. This function takes a timetuple() of the datetime object and converts it into the number of seconds since the Unix epoch. This function ensures that the conversion remains consistent across time zones.

Python
import datetime
import calendar

t=datetime.datetime(2021, 7, 7, 1, 2, 1)
print(calendar.timegm(t.timetuple()))

Output:

1625619721

Converting Epoch to Datetime

To convert epoch time back to a human-readable datetime format we can use the datetime.fromtimestamp() function. Below is the code to implement it.

Python
import datetime  
epoch = 33456871 

epoch_date_time = datetime.datetime.fromtimestamp(epoch)   
print("Converted Datetime:", epoch_date_time )  

Output:

Converted Datetime: 1971-01-23 05:34:31

Handling Time Zones

When working with datetime objects that include timezone information it’s essential to ensure that the conversion reflects UTC time accurately. You can create timezone-aware datetime objects using the timezone class from the datetime module.

Python
from datetime import datetime, timezone

dt = datetime(2024, 1, 1, 0, 0, tzinfo=timezone.utc)
epoch_time = dt.timestamp()
print(epoch_time)

Output:

1704067200.0

Converting Python datetime to epoch time is straightforward using the timestamp() method. The calendar module is also a great alternative for UTC-specific conversions.


Next Article

Similar Reads