Convert Unix timestamp to DateTime in python

Convert unix timestamp to datetime in Python

A UNIX timestamp is defined as the several numbers of seconds between a particular date and the Epoch i.e January 1, 1970 at UTC.

In this tutorial, we will see some methods by which we can convert a UNIX timestamp to DateTime in Python.

Using fromtimestamp() Function

DateTime module in python is used to deal with the date and time-related problems in python.

One of the functions in this module is the fromtimestamp() function. This function returns the time that is expressed as seconds i.e UNIX timestamp.

Example 1:

Output:

dateAndtime: 2019-08-02 12:13:43

Here, we first import the datetime class from the datetime module. Then we store the UNIX value object in a variable. After that, we use the datetime.fromtimestamp() function that will get us the time and date. Finally, we print the unix_val variable.

To get the current timestamp, we use the now() function from the datetime module.

Output:

current timestamp = 1621358136.138725

To convert this again to DateTime, we use the same code from example 1.

Using strftime() Function

Another function in the datetime module is the strftime() function. This function helps in returning the DateTime in a specific form. To convert the date and time objects to their string representation, this function is generally used.

Example:

Output:

Converted date and time: 2019-08-02 12:13:43

In the above code, %d, %m, %Y, %H, %M and %S are called format codes which represent days, month, year, hour, minutes, and seconds respectively. In this code also, fromtimestamp() is used to return the time that is expressing in the UNIX timestamp.

Using to_datetime() Function

This function comes under the Pandas library in python. Pandas is one of the most common libraries in python. This library helps in manipulating and analyze data and is widely used in the field of data science.

The to_datatime() of the Pandas library helps in converting a Unix timestamp to DateTime in Python.

Example:

Output:

2019-08-02 06:43:43

In this method, we first start by importing the Pandas which is pre-installed in python. Then we make a variable ‘timestamp’ to store the UNIX timestamp that has to converted. After that, we use the to_datetime function. Note that, in the argument of the to_datetime function, we have mentioned the unit equal to ‘s’. The unit variable represents the unit of the UNIX timestamp i.e seconds.

That’s all about how to convert UNIX timestamp to DateTime in Python.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *