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.

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.

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.

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

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