⏱️UnixTime

Unix Timestamp & Time Tools

Converter • Age Calculator • Countdown Timer • Batch Tools

Python Unix Timestamp Guide

A comprehensive guide to working with Unix timestamps in Python. Learn how to get the current timestamp, convert between timestamps and datetime objects, handle timezones, and more.

Quick Reference

Get Current Timestamp

time.time()

Timestamp to Datetime

datetime.fromtimestamp(ts)

Datetime to Timestamp

dt.timestamp()

Current UTC Time

datetime.utcnow()

Getting the Current Unix Timestamp

The simplest way to get the current Unix timestamp in Python is using the time module:

import time

# Get current timestamp (seconds since Jan 1, 1970)
timestamp = time.time()
print(timestamp)  # Output: 1733616000.123456

# Get timestamp as integer (no decimal)
timestamp_int = int(time.time())
print(timestamp_int)  # Output: 1733616000

Note: time.time() returns a float with microsecond precision. Use int() to get whole seconds.

Converting Timestamp to Datetime

Convert a Unix timestamp to a human-readable datetime object:

from datetime import datetime

# Convert timestamp to datetime (local timezone)
timestamp = 1733616000
dt = datetime.fromtimestamp(timestamp)
print(dt)  # Output: 2024-12-07 18:00:00

# Convert timestamp to datetime (UTC)
dt_utc = datetime.utcfromtimestamp(timestamp)
print(dt_utc)  # Output: 2024-12-07 18:00:00

# Format the datetime
formatted = dt.strftime('%Y-%m-%d %H:%M:%S')
print(formatted)  # Output: 2024-12-07 18:00:00

Converting Datetime to Timestamp

Convert a datetime object back to a Unix timestamp:

from datetime import datetime

# Current datetime to timestamp
now = datetime.now()
timestamp = now.timestamp()
print(timestamp)  # Output: 1733616000.123456

# Specific date to timestamp
dt = datetime(2024, 12, 7, 18, 0, 0)
timestamp = dt.timestamp()
print(timestamp)  # Output: 1733616000.0

# String date to timestamp
date_string = "2024-12-07 18:00:00"
dt = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
timestamp = dt.timestamp()
print(timestamp)  # Output: 1733616000.0

Working with Timezones

Handle timezone-aware timestamps using the pytz library:

from datetime import datetime
import pytz

# Create timezone-aware datetime
utc = pytz.UTC
eastern = pytz.timezone('US/Eastern')

# Get current time in specific timezone
now_utc = datetime.now(utc)
now_eastern = datetime.now(eastern)

# Convert timestamp to timezone-aware datetime
timestamp = 1733616000
dt_utc = datetime.fromtimestamp(timestamp, utc)
dt_eastern = datetime.fromtimestamp(timestamp, eastern)

print(dt_utc)      # 2024-12-07 18:00:00+00:00
print(dt_eastern)  # 2024-12-07 13:00:00-05:00

# Convert between timezones
dt_converted = dt_utc.astimezone(eastern)
print(dt_converted)  # 2024-12-07 13:00:00-05:00

Installation: Install pytz with pip install pytz

Milliseconds and Microseconds

Working with higher precision timestamps:

import time
from datetime import datetime

# Get timestamp in milliseconds
timestamp_ms = int(time.time() * 1000)
print(timestamp_ms)  # Output: 1733616000123

# Get timestamp in microseconds
timestamp_us = int(time.time() * 1000000)
print(timestamp_us)  # Output: 1733616000123456

# Convert milliseconds to datetime
ms_timestamp = 1733616000123
dt = datetime.fromtimestamp(ms_timestamp / 1000)
print(dt)  # Output: 2024-12-07 18:00:00.123000

# Convert microseconds to datetime
us_timestamp = 1733616000123456
dt = datetime.fromtimestamp(us_timestamp / 1000000)
print(dt)  # Output: 2024-12-07 18:00:00.123456

Common Use Cases

Calculate Time Difference

from datetime import datetime

# Calculate difference between two timestamps
timestamp1 = 1733616000
timestamp2 = 1733619600

diff_seconds = timestamp2 - timestamp1
diff_hours = diff_seconds / 3600
diff_days = diff_seconds / 86400

print(f"Difference: {diff_seconds} seconds")
print(f"Difference: {diff_hours} hours")
print(f"Difference: {diff_days} days")

Get Start of Day Timestamp

from datetime import datetime, time as dt_time

# Get timestamp for start of today (00:00:00)
now = datetime.now()
start_of_day = datetime.combine(now.date(), dt_time.min)
timestamp = start_of_day.timestamp()

print(timestamp)  # Start of today at midnight

Validate Timestamp Range

from datetime import datetime

def is_valid_timestamp(timestamp):
    """Check if timestamp is within valid range"""
    try:
        # Check if timestamp is reasonable (between 1970 and 2100)
        min_ts = 0  # Jan 1, 1970
        max_ts = 4102444800  # Jan 1, 2100

        if min_ts <= timestamp <= max_ts:
            dt = datetime.fromtimestamp(timestamp)
            return True
        return False
    except (ValueError, OSError):
        return False

print(is_valid_timestamp(1733616000))  # True
print(is_valid_timestamp(-1000))       # False
print(is_valid_timestamp(9999999999))  # False

Best Practices

Always store timestamps in UTC

Convert to local timezone only for display purposes.

Use datetime for date arithmetic

Convert timestamps to datetime objects when you need to add/subtract time.

Be aware of the Year 2038 problem

Python handles this well with 64-bit integers, but be careful when interfacing with systems that don't.

Use integers for database storage

Store timestamps as INTEGER (Unix timestamp) for better performance and portability.

Consider using milliseconds for precision

For high-frequency events or precise timing, use millisecond timestamps.

Related Tools