Epoch and Date Time Conversion in Python

Python is a high level general purpose programming langauge. It's language constructs and object-oriented approach helps programmers to write clear and logical code for small and large-scale projects. Python has datetime module which supplies classes to deal with dates, times and time intervals. So with Paython, we can easily handle epoch or Unix timestamp conversion into human readable dates or can convert human readable dates to Unix timestamp.

Here we will explain Python datetime classes to get current epoch or Unix timestamp, convert timestamp to date and convert date to epoch or Unix timestamp.

Get current epoch or Unix timestamp in Python

We can get the current epoch or timestamp using Python time() module. It will returns the current epoch in the number of seconds.

import time
print int(time.time())


Output
1585990763

Convert epoch or Unix timestamp to human readable date in Python

We can convert the epoch or timestamp to readable date format using Python time() module. The function formats and return epoch or timestamp to human readable date and time.

import time
timestamp = "1585990763"
time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(timestamp))

Output
2020-04-04 02:35:07

Convert date to epoch or unix timestamp in Python

We can convert human readable date to timestamp using Python datetime class and function strptime. The function convert English textual datetime into a Unix timestamp.

import datetime
myDate = "2020-04-04"
print(datetime.datetime.strptime(myDate, "%d/%m/%Y").timestamp())

Output
1585990763


More about date time in Python