Timestamp to datetime Python

To convert a timestamp to a datetime object in Python, you can use the datetime module from the standard library. Here's an example:

import datetime

# Convert timestamp to datetime object
timestamp = 1645967700
dt_object = datetime.datetime.fromtimestamp(timestamp)

# Print the datetime object
print("Datetime object:", dt_object)
Sourc‮www:e‬.theitroad.com

This will output the datetime object in the following format:

Datetime object: 2022-02-28 10:35:00

In this example, we used the fromtimestamp() method of the datetime class to convert the timestamp to a datetime object. The timestamp argument is the Unix timestamp that represents the number of seconds since the Unix epoch (January 1, 1970, 00:00:00 UTC).

If you want to display the datetime object in a specific format, you can use the strftime() method. Here's an example:

import datetime

# Convert timestamp to datetime object
timestamp = 1645967700
dt_object = datetime.datetime.fromtimestamp(timestamp)

# Format the datetime object
formatted_datetime = dt_object.strftime("%Y-%m-%d %H:%M:%S")

# Print the formatted datetime
print("Formatted datetime:", formatted_datetime)

This will output the formatted datetime in the following format:

Formatted datetime: 2022-02-28 10:35:00

In this example, the %Y, %m, and %d codes represent the year, month, and day respectively, while the %H, %M, and %S codes represent the hour, minute, and second respectively. You can use different codes to format the datetime in a different way.