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 |
epoch_time_x_1 = 3128275 print(epoch_time_x_1) # 3128275
Next, we can load the datetime module as shown below:
import datetime |
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 |
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 |
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 |
epoch_time_x_2 = datetime_x_2.timestamp() print(epoch_time_x_2) # 703159680.0
Further Resources
Please find some related tutorials below.
- Set datetime to Different Time Zone in Python (3 Examples)
- Set datetime Object to Date Only String in Python (3 Examples)
- Transform datetime Object to Date & Vice Versa in Python (2 Examples)
- Transform datetime Object to Hours Minutes or Seconds in Python (3 Examples)
- Modify datetime Format in pandas DataFrame in Python (2 Examples)
- All Python Programming Tutorials
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.