English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Python

Python Flow Control

Fonction en Python

Types de données en Python

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Python Knowledge

Python Reference Manual

Timestamp (timestamp) en Python

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

Example1: Python timestamp to date and time

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.

Example2: Python date and time to timestamp

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)