Convert the timestamp value in Python
In this article, TipsMake.com will show you how to convert the timestamp value into a datetime object and a datetime object into a timestamp value in Python, along with specific examples to make it easier to visualize and capture this value. better.
In databases, storing dates and times as timestamp values is quite common.
Unix timestamp or Unix time is the system that expresses a point on the time axis, using the number of seconds to determine the time, with the starting point from 00:00:00 on January 1, 1970 in UTC time.
Example: At 13:54:27 - 21/05/2019 has a timestamp value of 1558446867; This means from 00:00 to 1/1/1970 to 13:54:27 - May 21, 2019 is 1558446867 seconds.
Example 1: Convert timestamp value to datetime
from datetime import datetime timestamp = 1562907183 dt_object = datetime.fromtimestamp(timestamp) print("dt_object =", dt_object) print("type(dt_object) =", type(dt_object))
Run the program, the result returns the date and time corresponding to the timestamp 1562907183 value :
dt_object = 2019-07-12 11:53:03 type(dt_object) =
Here, we import the datetime class from the datetime module and then use the datetime.fromtimestamp () method to return the local date and time ( datetime object ) stored in the dt_object variable .
You can easily create a time display string using the strftime method ().
Example 2: Convert datetime to timestamp value
You can retrieve the timestamp value from a datetime object using the method datetime.timestamp ().
from datetime import datetime # ngay gio hien tai now = datetime.now() timestamp = datetime.timestamp(now) print("timestamp =", timestamp) print("Ngay gio hien tai:", now)
Result:
timestamp = 1562915824.395594 Ngay gio hien tai: 2019-07-12 14:17:04.395594
Previous lesson: Current date and time in Python
Next lesson: Module time in Python
You should read it
- CURRENT_TIMESTAMP command in SQL Server
- Datetime in Python
- Strptime () function in Python
- Strftime () function in Python
- Module time in Python
- Current date and time in Python
- How to Comment with Timeline on YouTube
- ObjectId in MongoDB
- Learn about Sigcheck of Microsoft
- Google introduces a new feature that makes it easy to find important moments in a video
- Function sleep () in Python
- SQL Server YEAR function