Explain Codes LogoExplain Codes Logo

In Python, how do you convert seconds since epoch to a datetime object?

python
datetime
timestamp
timezone
Nikita BarsukovbyNikita Barsukov·Feb 24, 2025
TLDR

To swiftly convert the epoch time to a datetime in Python, simply use:

from datetime import datetime # Behold: The magical time portal! datetime.fromtimestamp(1633076672) # Poof! Your timestamp is now a datetime object!

Don't forget to replace 1633076672 with your actual timestamp.

However, things can get a little tricky when dealing with different time zones. Fear not, here's how to convert it correctly for local time or UTC.

Converting in different time zones and UTC

When dealing with time zones, transform your timestamp for the correct local time or UTC:

from datetime import datetime, timezone datetime.fromtimestamp(1633076672, timezone.utc) # Neither snow nor rain nor heat nor gloom of timezone confusions...

For strict UTC time, use utcfromtimestamp():

datetime.utcfromtimestamp(1633076672) # This way, you're never late for the tea time in London.

Remember, if you're dealing with dates before 1970 on Windows (where epoch times were still a glimmer in Ken Thompson's eye), stick with utcfromtimestamp.

Formatting the datetime monster

Done with conversion? Great! Now let's polish the datetime object for readability. Use the strftime() method:

datetime.fromtimestamp(1633076672).strftime('%Y-%m-%d %H:%M:%S') # Stringifying datetime is like getting properly dressed for a time travel.

Prettier now, isn't it?

Dealing with outliers

Here are a few heads-ups when working with timestamps:

  • Negative epochs: Unix can take it, but Windows might give you the cold shoulder.

  • ISO 8601 format: Use isoformat() – because even robots need standards.

    datetime.fromtimestamp(1633076672, timezone.utc).isoformat() # Like saying datetime in tuxedo.
  • Platform-specific issues: Always have this in mind. An Apple a day keeps the doctor away, but Microsoft might still give you headaches.

Pitfall alert! Watch out for the ValueError

Some timestamps can be out of the range of values supported by the platform's datetime library, and using fromtimestamp might raise a ValueError. Always have a try...except safety net.

Working secret gears: Python 2 & peeping into extra libraries

Python 2 compatibility

The menacing compatibility issues with Python 2 can be pacified using the pytz library for timezone conversions:

import pytz # Backwards compatibility? No problemo! datetime.fromtimestamp(1633076672, pytz.utc)

Helper libraries at your service

There's a whole cavalry of third-party libraries like Arrow and dateutil for easy handling of dates and times:

import arrow # Arrow knows how to hit the bullseye! arrow.get(1633076672).to('US/Pacific')

And always remember to import those modules (datetime, timezone, pytz...), or the Python interpreter might act like a doorman keeping you out of your own party.