Convert Datetime to Timestamp in Python

To convert datetime to timestamp, first, you have to import the datetime module, assign datetime to a variable and use the timestamp function to convert it into a timestamp.

from datetime import datetime

my_datetime = datetime(2021, 6, 14, 12, 33, 41)
timestamp = my_datetime.timestamp()

print("timestamp:", timestamp)
print("datetime:", my_datetime)

If you run the code, both, the timestamp and datetime are printed.

timestamp: 1623666821.0
datetime: 2021-06-14 12:33:41

Convert timestamp to datetime

To convert a timestamp to a datetime, you have to assign the timestamp to a variable. Next, the variable has to be converted to the datetime object.

from datetime import datetime

timestamp = 1435634284
my_datetime = datetime.fromtimestamp(timestamp)

print("datetime:", my_datetime)
print("timestamp:", timestamp)
print("type(my_datetime): ", type(my_datetime))

If you run the code, you’ll see that the supposedly meaningless string of characters returned date and time.

The last line prints the type of the variable.

datetime: 2015-06-30 05:18:04
timestamp: 1435634284
type(my_datetime):

Convert the current timestamp

In the previous example, we used a ti+mestamp value that returned a date somewhere in 2015. If you want to get the current timestamp, you can get the current datetime and convert it to the timestamp, using the time() function.

from datetime import datetime
from time import time

timestamp = time()
my_datetime = datetime.fromtimestamp(timestamp)

print("timestamp:", timestamp)
print("datetime:", my_datetime)
print("type(my_datetime): ", type(my_datetime))

This code returns the current timestamp represented by the float value.

timestamp: 1623686864.2045426
datetime: 2021-06-14 18:07:44.204543
type(timestamp):