Set Epoch Time to datetime Object & Vice Versa in Python (2 Examples)

On this site, you’ll see how to transform an epoch time into a datetime object and vice versa in the Python language.

Example 1: Set Epoch Time to datetime Object

Consider the following epoch time object:

epoch_time_x_1 = 3128275
print(epoch_time_x_1)
# 3128275

Next, we can load the datetime module as shown below:

import datetime

For the conversion, we have to specify the epoch time data object as a parameter within the fromtimestamp() function:

datetime_x_1 = datetime.datetime.fromtimestamp(epoch_time_x_1)
print(datetime_x_1)
# 1970-02-06 05:57:55

A new datetime object has been created containing the date and time corresponding to our epoch time.

Example 2: Set datetime Object to Epoch Time

This example shows how to transform a datetime object into an epoch time.

First, we have to create a datetime object:

datetime_x_2 = datetime.datetime(1992, 4, 13, 12, 8)
print(datetime_x_2)
# 1992-04-13 12:08:00

Then we can apply the timestamp() function to convert our datetime object to an epoch time:

epoch_time_x_2 = datetime_x_2.timestamp()
print(epoch_time_x_2)
# 703159680.0

 

Further Resources

Please find some related tutorials below.

 

Matthias Bäuerlen Python Programmer

Note: This article was created in collaboration with Matthias Bäuerlen. Matthias is a programmer who helps to create tutorials on the Python programming language. You might find more info about Matthias and his other articles on his profile page.

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top