How to Get Epoch Timestamps in Python
Complete guide to working with epoch timestamps in Python. Use time, datetime, and calendar modules to get, convert, and format Unix timestamps.
Programming
Detailed Explanation
Epoch Timestamps in Python
Python provides multiple modules for working with epoch timestamps: time, datetime, and calendar. Python uses seconds (with optional fractional precision) as its native epoch format.
Getting the Current Epoch
import time
from datetime import datetime
# Seconds with fractional precision
time.time() # 1705312200.123456
# Integer seconds
int(time.time()) # 1705312200
# Using datetime
datetime.now().timestamp() # 1705312200.123456
Converting Epoch to Datetime
from datetime import datetime, timezone
# To local datetime
dt = datetime.fromtimestamp(1705312200)
print(dt) # 2024-01-15 09:30:00 (local timezone)
# To UTC datetime (recommended)
dt_utc = datetime.fromtimestamp(1705312200, tz=timezone.utc)
print(dt_utc) # 2024-01-15 09:30:00+00:00
# Format as string
dt_utc.strftime("%Y-%m-%d %H:%M:%S") # "2024-01-15 09:30:00"
dt_utc.isoformat() # "2024-01-15T09:30:00+00:00"
Converting Datetime to Epoch
from datetime import datetime, timezone
import calendar
# From datetime object
dt = datetime(2024, 1, 15, 9, 30, 0, tzinfo=timezone.utc)
epoch = int(dt.timestamp()) # 1705312200
# From string
dt = datetime.strptime("2024-01-15 09:30:00", "%Y-%m-%d %H:%M:%S")
epoch = int(dt.replace(tzinfo=timezone.utc).timestamp())
# Using calendar (for UTC tuples)
epoch = calendar.timegm((2024, 1, 15, 9, 30, 0, 0, 0, 0))
Countdown Calculation
from datetime import datetime, timezone
target = datetime(2025, 1, 1, 0, 0, 0, tzinfo=timezone.utc)
now = datetime.now(timezone.utc)
remaining = target - now # timedelta object
days = remaining.days
hours = remaining.seconds // 3600
minutes = (remaining.seconds % 3600) // 60
seconds = remaining.seconds % 60
Important: Timezone Awareness
Always use timezone-aware datetimes (timezone.utc) when converting to/from epoch. Naive datetimes assume local time, which can cause subtle bugs in production when servers run in different timezones.
Use Case
Use this reference when building backend services, data pipelines, or scripts in Python that need to work with Unix timestamps. It covers all the common conversion patterns and the critical timezone-awareness pitfall.