English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, you will learn how to convert a timestamp to a datetime object, and convert a datetime object to a timestamp (through examples).
It is common to store dates and times as timestamps in databases. Unix timestamp is the specific date to UTC1970 years1Months1Seconds between days
from datetime import datetime timestamp = 1545730073 dt_object = datetime.fromtimestamp(timestamp) print("dt_object =", dt_object) print("type(dt_object) =", type(dt_object))
The output when running the program is:
dt_object = 2018-12-25 09:27:53 type(dt_object) = <class 'datetime.datetime'>
Here, we gotdatetimeThe datetime class was imported from the module. Then, we used the datetime.fromtimestamp() class method, which returns the local date and time (datetime object). This object is stored indt_objectin variables.
Note:You can usestrftime()The method can easily create a string representing the date and time from a datetime object.
You can use the datetime.timestamp() method to get the timestamp from a datetime object.
from datetime import datetime # Current date and time now = datetime.now() timestamp = datetime.timestamp(now) print("Timestamp =", timestamp)