How to convert epoch time to MySQL datetime format in Python?

How can I Python convert epoch to datetime? I am getting a response from the REST API in Epoch time format, like this:

start_time = 1234566
end_time = 1234578

I want to convert these epoch seconds into a MySQL-compatible datetime format to store the differences in my MySQL database.

I tried this:

import time
time.gmtime(123456)

The result I get is:

time.struct_time(tm_year=1970, tm_mon=1, tm_mday=2, tm_hour=10, tm_min=17, tm_sec=36, tm_wday=4, tm_yday=2, tm_isdst=0)

This is not the format I was expecting. I want the result to be like:

2012-09-12 21:00:00

Please suggest how I can achieve this.

Also, I am getting a TypeError: a float is required when trying this:

getbbb_class.end_time = 1347516459425
mend = time.gmtime(getbbb_class.end_time).tm_hour

Why am I getting this error?

Hey, from my experience with date and time handling in Python, I’ve often used the datetime module to easily convert epoch time into a human-readable format. Here’s how I usually do it:

import datetime

start_time = 1234566
end_time = 1234578

# python convert epoch to datetime
start_datetime = datetime.datetime.fromtimestamp(start_time).strftime('%Y-%m-%d %H:%M:%S')
end_datetime = datetime.datetime.fromtimestamp(end_time).strftime('%Y-%m-%d %H:%M:%S')

print("Start Time:", start_datetime)
print("End Time:", end_datetime)

This should give you the format you’re looking for, like 2012-09-12 21:00:00. It’s a pretty straightforward way to handle it!

Great example, @macy-davis! If you’re looking for an alternative or just prefer the time module over datetime, I personally use it quite often. It also works fine for converting epoch to MySQL datetime in Python. Here’s how I would approach it:

import time

start_time = 1234566
end_time = 1234578

# python convert epoch to datetime
start_datetime = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(start_time))
end_datetime = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(end_time))

print("Start Time:", start_datetime)
print("End Time:", end_datetime)

This method will give you a similar output (2012-09-12 21:00:00) but uses a slightly different approach. time.gmtime() is great for this and avoids needing fromtimestamp() from the datetime module.

Nice approach, @shilpa.chandel! Just wanted to add a little heads-up, as I’ve run into an issue myself when using time.gmtime(). If you happen to get a TypeError like ‘a float is required,’ it’s usually because the epoch time you’re passing isn’t a float. Make sure you have it in the correct format.

For example, I had an epoch value like this:

import time

# python convert epoch to datetime
getbbb_class_end_time = 1347516459425.0  # Ensure it’s a float
mend = time.gmtime(getbbb_class_end_time).tm_hour

print("Hour:", mend)

By converting it to a float (1347516459425.0), I was able to extract the time correctly without errors. This should work seamlessly and keep your calculations on track!