Convert Unix Epoch/Timestamp to Datetime in Python

To convert a Unix timestamp to a formatted date in Python, use either the time or datetime package.

 

Convert Epoch with the time Package

The time package has a collection of functions for working with dates and times including the ability to convert Unix epochs into human-readable dates. One such function is time.localtime() which takes an epoch and returns a key-value pair time object.

 

Here is an example of how to use the time.localtime() function.

 

import time

epoch = 1625762090
time_obj = time.localtime(epoch)

print(type(time_obj))
print(time_obj)
<class 'time.struct_time'>
time.struct_time(tm_year=2021, tm_mon=7, tm_mday=8, tm_hour=17, tm_min=34, tm_sec=50, tm_wday=3, tm_yday=189, tm_isdst=1)

 

You could build a date string from this object by accessing the values like this:

 

time_str = str(time_obj.tm_year) + '/' + str(time_obj.tm_mon) + '/' + str(time_obj.tm_mday)

print(time_str)
2021/7/8

 

Or even extract the values you need and create a standard Python tuple like this:

 

time_tuple = time_obj.tm_year, time_obj.tm_mon, time_obj.tm_mday

print(time_tuple)
(2021, 7, 8)

 

Formatting Dates with strftime()

The time.strftime() function will format a date converted with time.localtime() according to the pattern provided. Let's take a look at how we might use it.

 

import time

epoch = 1625762090
time_obj = time.localtime(epoch)

time_str = time.strftime('%Y-%m-%d %H:%M:%S', time_obj)

print(time_str)
2021-07-08 17:34:50

 

Convert Epoch with the datetime Package

Yet another way to convert a Unix timestamp is to use the datetime package like this:

 

import datetime

epoch = 1625762090

time_str = datetime.datetime.fromtimestamp(epoch).strftime('%A, %B %-d, %Y %H:%M:%S')

print(time_str)
Thursday, July 8, 2021 17:34:50