Python

Unix Timestamps in Python

Handle Unix timestamps in Python with datetime, time modules - conversion, formatting, and timezone handling.

Try Unix Timestamp Converter →

Code Example

import datetime
import time

# Current Unix timestamp
timestamp = int(time.time())
print(timestamp)

# Current timestamp (with microseconds)
timestamp_float = time.time()

# Timestamp to datetime
ts = 1704067200
dt = datetime.datetime.fromtimestamp(ts)
print(dt)  # 2024-01-01 00:00:00

# Timestamp to UTC datetime
dt_utc = datetime.datetime.utcfromtimestamp(ts)

# Datetime to timestamp
now = datetime.datetime.now()
ts_now = int(now.timestamp())

# Parse string to datetime
dt = datetime.datetime.strptime('2025-01-27', '%Y-%m-%d')
ts = int(dt.timestamp())

# Format datetime
formatted = dt.strftime('%B %d, %Y')  # 'January 27, 2025'

# Add days
future = dt + datetime.timedelta(days=7)

# Difference between dates
diff = (dt2 - dt1).days

# With timezone (Python 3.9+)
from zoneinfo import ZoneInfo
dt_tz = datetime.datetime.now(ZoneInfo('America/New_York'))

# ISO format
iso = dt.isoformat()  # '2025-01-27T00:00:00'
Key Points: Use datetime module for date manipulation, time.time() for current timestamp. timedelta for arithmetic, strftime/strptime for formatting.

Related Examples

More Python Examples