Last updated
Common Mistakes
utcfromtimestamp()returns a naive datetime — attach timezone info for timezone-aware code- Millisecond timestamps need to be divided by 1000 before passing to datetime functions
- Mixing naive and aware datetimes raises a TypeError — be consistent throughout your code
- Always store and process timestamps in UTC; only convert to local time for display
Use the Epoch Converter tool to verify your Python conversions instantly.
Examples
Example 1: Basic Conversion with datetime Module
from datetime import datetime
unix_timestamp = 1710000000 # seconds since epoch
# Convert to UTC datetime
utc_date = datetime.utcfromtimestamp(unix_timestamp)
print(utc_date)
# 2024-03-09 21:20:00
# Convert to local system timezone
local_date = datetime.fromtimestamp(unix_timestamp)
print(local_date)
# 2024-03-09 22:20:00 (if you're in UTC+1)
Example 2: Formatting the Date with strftime
from datetime import datetime
ts = 1710000000
date = datetime.utcfromtimestamp(ts)
# ISO 8601 format
print(date.strftime('%Y-%m-%dT%H:%M:%SZ'))
# 2024-03-09T21:20:00Z
# Human-readable
print(date.strftime('%B %d, %Y at %I:%M %p'))
# March 09, 2024 at 09:20 PM
# Date only
print(date.strftime('%Y-%m-%d'))
# 2024-03-09
# Common format codes:
# %Y = 4-digit year %m = 2-digit month %d = 2-digit day
# %H = 24h hour %M = minutes %S = seconds
# %I = 12h hour %p = AM/PM %A = weekday name
Example 3: Handling Millisecond Timestamps
JavaScript and many modern APIs return timestamps in milliseconds. Divide by 1000 before converting:
from datetime import datetime
# Millisecond timestamp (13 digits)
ms_timestamp = 1710000000000
# Divide by 1000 to get seconds
date = datetime.utcfromtimestamp(ms_timestamp / 1000)
print(date)
# 2024-03-09 21:20:00
# Helper function that handles both
def to_datetime(timestamp):
if timestamp > 1e12: # milliseconds
return datetime.utcfromtimestamp(timestamp / 1000)
return datetime.utcfromtimestamp(timestamp)