Timestamp to datetime conversion in Python

In this article, we will see the conversion of a timestamp to datetime and vice-versa in Python language.
This can be done using the datetime module, so let’s go ahead and import the same.

from datetime import datetime

The fromtimestamp() function from the datetime module can be used to get a date from a UNIX (seconds) timestamp.

datetime.datetime(2020, 7, 23, 12, 19, 59)

Let’s put this in a more readable manner.

date_now = datetime.fromtimestamp(1595486999)
<class 'datetime.datetime'>

The date_now variable used to store the date from the timestamp becomes a datetime object.

Also, you might be thinking how did I get the UNIX value. For that, we can use the timestamp() function.


For instance, the datetime.now() function gives us the current date and time, which is then converted into a UNIX value with the help of timestamp().

We can play around and present the output in various datetime formats.

Thu Jul 23 12:19:59 2020
print(date_now.strftime('%Y-%m-%d %H:%M:%S'))
2020-07-23 12:19:59
print(date_now.strftime('%x %X'))
07/23/20 12:19:59

You can also read,
Display various Datetime formats using Python
Remove seconds from the datetime in Python

Leave a Reply

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