Explain Codes LogoExplain Codes Logo

Converting Epoch time into the datetime

python
datetime
timestamp
timezones
Anton ShumikhinbyAnton Shumikhin·Nov 28, 2024
TLDR

One-liner to convert epoch time to datetime in Python using datetime.fromtimestamp():

from datetime import datetime print(datetime.fromtimestamp(1633072800)) # Outputs the equivalent datetime object

Accounting for Time Zones

While dealing with epoch time, remember to factor in time zones. For UTC conversion, simply switch to utcfromtimestamp():

from datetime import datetime print(datetime.utcfromtimestamp(1633072800)) # UCT time coming right up!

Guard against TypeError by ensuring your epoch time is a float or an int:

epoch_time = float('1633072800') print(datetime.fromtimestamp(epoch_time)) # Friendly TypeError, you shall not pass!

String Formatting the DateTime

Yearning for a custom datetime format? Leverage Python's strftime:

formatted_time = datetime.fromtimestamp(epoch_time).strftime('%d/%m/%Y %I:%M:%S %p') print(formatted_time) # Now that's a date to remember!

Ensuring Meaningful Input

Watch out for functions fromtimestamp() as they're picky about what input data types:

epoch_time = float('1633072800') human_time = datetime.fromtimestamp(epoch_time) # TypeError dodged, again!

Working with MySQL

In SQL-land, convert epoch time to MySQL time using FROM_UNIXTIME:

SELECT FROM_UNIXTIME(1633072800); # SQL, meet Epoch.

Need just the hour from epoch time? Here's how:

import time hour = time.gmtime(epoch_time).tm_hour print(hour) # Time's flying!

Epoch Time of Present

Get the current epoch time in a jiffy:

import time current_epoch_time = time.time() print(current_epoch_time) # Time now, chef's special!