How to convert timestamp to datetime and vice-versa in Python?
In this article, you will learn how to convert timestamp to datetime object and datetime object to timestamp.
It is common to store date and time as a timestamp in a database.
A Unix timestamp is the number of seconds between a specific date and January 1, 1970 at UTC.
Example: Python timestamp to datetime
In the following example, we will convert a timestamp to a datetime object.
from datetime import datetime
timestamp = 1494654246
dt_obj = datetime.fromtimestamp(timestamp)
print("dt_obj =", dt_obj)
print("type(dt_obj) =", type(dt_obj))
After running the above program, the output will be:
dt_obj = 2017-05-13 05:44:06
type(dt_obj) = <class 'datetime.datetime'>
In the program above, we imported datetime
class from the datetime module. Then, we used datetime.fromtimestamp()
class method that returns the local date and time (datetime object). This object is stored in dt_obj
variable.
Note: We can also create a string representing date and time from a
datetime
object using strftime() method.
Example: Python datetime to timestamp
We can get a timestamp from a datetime object using the datetime.timestamp()
method.
from datetime import datetime
now = datetime.now()
timestamp = datetime.timestamp(now)
print("timestamp =", timestamp)
Output
timestamp = 1635866119.849948