Python Epoch

The 'epoch' is the point where the time starts. This point is taken as the 0.0 hours of January 1st of the current year. For Unix, the epoch is 0.0 hours of January 1st of 1970. It is possible to measure the time in seconds since the epoch using time() function of 'time' module.

Convert Seconds to Epoch

CopiedCopy Code

#knowing the time since the epoch 
import time 
epoch = time.time() 
#call time() function of time module 
print(epoch)

Please observe the output of the previous program. This indicates how many seconds are gone since the epoch, i.e. since the beginning of the current year. This number is not that much useful unless we see it in the form of date and time. To convert these seconds into date and time, we can use localtime() function of 'time' module as:

dt = time.localtime(seconds-since-epoch)

This function returns an object similar to C language structure by the name 'struct_time'. From this object, it is possible to access the attributes either using an index or using a name. For example, to access the year number, we can use the index value 0 or the name: tm_year.

Table : The 'struct_time' Indexes and Related Attributes

Index Attribute Values
0 tm_year 4 digit year number like 2016
1 tm_mon range[1,12]
2 tm_mday range[1,31]
3 tm_hour range[0,23]
4 tm_min range[0,59]
5 tm_sec range[0,61],including leap seconds
6 tm_wday range[0,6],Monday is 0
7 tm_yday range[1,366]
8 tm_isdst [0,1 or -1],0=no DST,1=DST is in effect,-1=not known
tm_zone timezone name

Convert Epoch to Date Time

CopiedCopy Code

#converting the epoch time into date and time 
import time 
#localtime() converts the epoch time into time_struct object t 
t = time.localtime(1462077746.917558) 
#retrieve the date from the structure t 
d = t.tm_mday 
m = t.tm_mon 
y = t.tm_year 
print('Current date is: --d - --d - --d' --(d, m, y)) 
#retrieve the time from the structure t 
h = t.tm_hour 
m = t.tm_min 
s = t.tm_sec 
print('Current time is: --d: --d: --d' --(h,m,s))

Another way to convert the epoch time into date and time is by using ctime() function of 'time' module.This function takes epoch time in seconds and returns corresponding date and time in string format.

Convert Date Time to Epoch

CopiedCopy Code

#convert epoch time into date and time using ctime() 
import time 
t = time.ctime(1462077746.917558) 
#ctime() with epoch seconds 
print(t)