Convert Epoch to Datetime in Python

In this article, we are going to learn how we can convert Epoch to data time object of Python. We will make use of the datetime module of Python to get the current date and time. Once we have the Epoch time then we will convert it to a Python date time by using the fromtimestamp() function.

What is Epoch?

Epoch, also known as Unix Time is method of date and time representation. It represents time by the number of seconds that have elapsed since 00:00:00 UTC on 1 January 1970,which is considered as the beginning of the Unix epoch.

Environment and Requirement:-
Python Interpreter
datetime Module
fromtimestamp() function

Python Program to Convert Epoch to Datetime

      import datetime
      my_epoch_time1 = 1672207200
      print(my_epoch_time1)
      my_date_time1 = datetime.datetime.fromtimestamp(my_epoch_time1)
      print(my_date_time1)

Output:

1672207200
2022-12-28 00:00:00

Code Explanation:-

  1. import datetime module.
  2. Used my_epoch_time1 as an object which stores any value.
  3. Then print command is used to print that value.
  4. Then, used “my_date_time1” as an object which is storing datetime.datetime.fromtimestamp(object),
    this is the specified timestamp for which the date is going to be returned.
  5. Then again used print command to get the output.