How to Convert a Timestamp Object to a Datetime Object in Python



Python


In this article, we show how to convert a timestamp object to a datetime object in Python.

A timestamp is a form of type that can be considered computer code in the sense that it's not very human readable (or readable at all).

For many things, Python natively returns the time as timestamps, meaning the computer knows the date and time of the specific attribute, but humans will not necessarily know.

Therefore, it is important to know how to convert timestamps to datetime objects.

So what does Python return as timestamps?

One such thing is when getting information about a file, such as the last access time, or the date of the last time the file was modified, or the time the file was created.

All of these times are returned as timestamps natively by Python.

In the code, we are going to get the last modified date of a file and then convert the time which is returned natively as a timestamp to a datetime.



So since we're obtaining files on the computer's directory, we have to import os, the operating system module.

We then import datetime .

We create a variable called lastmodified, which gets the last date and time the file, file.txt, was modified.

We then print out the datetime version of this timestamp.

The phrase to do this is, datetime.fromtimestamp('parameter')

This will convert the timestamp to a datetime object.

And this is really all that is necessary to convert a timestamp to a datetime object


Related Resources



HTML Comment Box is loading comments...