🔢 Working with Timestamps
Unix timestamps are a universal way to represent time as seconds since January 1, 1970 (Unix epoch). They're essential for APIs, databases, and system integration. Python provides seamless conversion between datetime objects and timestamps.
import time
from datetime import datetime
# Get current timestamp
current_timestamp = time.time()
current_dt_timestamp = datetime.now().timestamp()
print(f"time.time(): {current_timestamp}")
print(f"datetime.timestamp(): {current_dt_timestamp}")
# Convert timestamp to datetime
dt_from_timestamp = datetime.fromtimestamp(current_timestamp)
print(f"From timestamp: {dt_from_timestamp}")
# Convert datetime to timestamp
dt = datetime(2024, 3, 15, 14, 30, 45)
timestamp = dt.timestamp()
print(f"DateTime {dt} → Timestamp: {timestamp}")
🎯 Understanding Unix Timestamps
Unix timestamps count seconds since the Unix epoch (January 1, 1970, 00:00:00 UTC).
Creating and Converting Timestamps
import time
from datetime import datetime
# Different ways to get current timestamp
timestamp1 = time.time() # Using time module
timestamp2 = datetime.now().timestamp() # Using datetime
print(f"time.time(): {timestamp1:.6f}")
print(f"datetime.now().timestamp(): {timestamp2:.6f}")
# Convert specific datetime to timestamp
specific_dt = datetime(2024, 1, 1, 0, 0, 0)
new_year_timestamp = specific_dt.timestamp()
print(f"New Year 2024 timestamp: {new_year_timestamp}")
# Convert timestamp back to datetime
back_to_dt = datetime.fromtimestamp(new_year_timestamp)
print(f"Back to datetime: {back_to_dt}")
Timestamp Precision
import time
from datetime import datetime
# Different timestamp precisions
current_time = datetime.now()
# Standard timestamp (seconds)
seconds_timestamp = int(current_time.timestamp())
print(f"Seconds: {seconds_timestamp}")
# Milliseconds timestamp (common in JavaScript)
milliseconds_timestamp = int(current_time.timestamp() * 1000)
print(f"Milliseconds: {milliseconds_timestamp}")
# Microseconds timestamp
microseconds_timestamp = int(current_time.timestamp() * 1_000_000)
print(f"Microseconds: {microseconds_timestamp}")
# Convert back from different precisions
from_seconds = datetime.fromtimestamp(seconds_timestamp)
from_milliseconds = datetime.fromtimestamp(milliseconds_timestamp / 1000)
from_microseconds = datetime.fromtimestamp(microseconds_timestamp / 1_000_000)
print(f"From seconds: {from_seconds}")
print(f"From milliseconds: {from_milliseconds}")
print(f"From microseconds: {from_microseconds}")
UTC vs Local Timestamps
from datetime import datetime, timezone
# Local timestamp
local_dt = datetime.now()
local_timestamp = local_dt.timestamp()
# UTC timestamp
utc_dt = datetime.now(timezone.utc)
utc_timestamp = utc_dt.timestamp()
print(f"Local datetime: {local_dt}")
print(f"Local timestamp: {local_timestamp}")
print(f"UTC datetime: {utc_dt}")
print(f"UTC timestamp: {utc_timestamp}")
# Convert timestamp to UTC datetime
utc_from_timestamp = datetime.fromtimestamp(local_timestamp, tz=timezone.utc)
print(f"UTC from timestamp: {utc_from_timestamp}")
# Convert timestamp to local datetime
local_from_timestamp = datetime.fromtimestamp(local_timestamp)
print(f"Local from timestamp: {local_from_timestamp}")
🛠️ Practical Timestamp Operations
Common operations you'll need when working with timestamps.
Timestamp Utilities
import time
from datetime import datetime, timezone
def current_timestamp_ms():
"""Get current timestamp in milliseconds"""
return int(time.time() * 1000)
def timestamp_to_datetime(timestamp, is_milliseconds=False):
"""Convert timestamp to datetime, handling both seconds and milliseconds"""
if is_milliseconds:
timestamp = timestamp / 1000
return datetime.fromtimestamp(timestamp)
def datetime_to_timestamp_ms(dt):
"""Convert datetime to milliseconds timestamp"""
return int(dt.timestamp() * 1000)
def is_valid_timestamp(timestamp, min_year=1970, max_year=2100):
"""Check if timestamp is within reasonable range"""
try:
dt = datetime.fromtimestamp(timestamp)
return min_year <= dt.year <= max_year
except (ValueError, OSError):
return False
# Example usage
current_ms = current_timestamp_ms()
print(f"Current timestamp (ms): {current_ms}")
# Test timestamp validation
test_timestamps = [
time.time(), # Valid current time
1234567890, # Valid past time (2009)
12345, # Invalid (too early)
9999999999, # Invalid (too late for 32-bit)
]
for ts in test_timestamps:
valid = is_valid_timestamp(ts)
if valid:
dt = timestamp_to_datetime(ts)
print(f"✓ {ts} → {dt}")
else:
print(f"✗ {ts} → Invalid timestamp")
Performance Timing
import time
from datetime import datetime
class Timer:
"""Simple performance timer using timestamps"""
def __init__(self):
self.start_time = None
self.end_time = None
def start(self):
"""Start timing"""
self.start_time = time.time()
print(f"Timer started at: {datetime.fromtimestamp(self.start_time)}")
def stop(self):
"""Stop timing and return duration"""
self.end_time = time.time()
duration = self.end_time - self.start_time
print(f"Timer stopped at: {datetime.fromtimestamp(self.end_time)}")
print(f"Duration: {duration:.6f} seconds")
return duration
def lap(self):
"""Get current duration without stopping"""
if self.start_time is None:
return 0
current_time = time.time()
return current_time - self.start_time
# Example usage
timer = Timer()
timer.start()
# Simulate some work
time.sleep(0.1)
lap_time = timer.lap()
print(f"Lap time: {lap_time:.3f} seconds")
time.sleep(0.1)
total_time = timer.stop()
Data Timestamping
import time
from datetime import datetime
import json
class TimestampedData:
"""Add timestamps to data for tracking"""
def __init__(self):
self.data = []
def add_entry(self, data, custom_timestamp=None):
"""Add data entry with timestamp"""
timestamp = custom_timestamp or time.time()
entry = {
'timestamp': timestamp,
'datetime': datetime.fromtimestamp(timestamp).isoformat(),
'data': data
}
self.data.append(entry)
return entry
def get_entries_between(self, start_time, end_time):
"""Get entries between two timestamps"""
return [
entry for entry in self.data
if start_time <= entry['timestamp'] <= end_time
]
def get_recent_entries(self, seconds=3600):
"""Get entries from last N seconds"""
cutoff = time.time() - seconds
return [
entry for entry in self.data
if entry['timestamp'] >= cutoff
]
def to_json(self):
"""Export data as JSON"""
return json.dumps(self.data, indent=2)
# Example usage
logger = TimestampedData()
# Add some sample data
logger.add_entry({"temperature": 22.5, "humidity": 65})
time.sleep(0.1)
logger.add_entry({"temperature": 23.1, "humidity": 63})
time.sleep(0.1)
logger.add_entry({"temperature": 22.8, "humidity": 64})
# Get recent entries
recent = logger.get_recent_entries(seconds=1)
print(f"Recent entries: {len(recent)}")
# Print formatted data
for entry in logger.data:
dt = datetime.fromtimestamp(entry['timestamp'])
print(f"{dt.strftime('%H:%M:%S')}: {entry['data']}")
📊 Timestamp Conversion Reference
Common Timestamp Formats
Format | Description | Example | Python Conversion |
---|---|---|---|
Unix (seconds) | Standard Unix timestamp | 1710519045 | time.time() |
Milliseconds | JavaScript/API common | 1710519045123 | int(time.time() * 1000) |
Microseconds | High precision | 1710519045123456 | int(time.time() * 1_000_000) |
ISO String | Human readable | 2024-03-15T14:30:45 | datetime.now().isoformat() |
API Integration Examples
import time
from datetime import datetime, timezone
import json
def prepare_api_data(data):
"""Prepare data for API submission with timestamps"""
return {
'timestamp': int(time.time()),
'timestamp_ms': int(time.time() * 1000),
'iso_timestamp': datetime.now(timezone.utc).isoformat(),
'data': data
}
def parse_api_response(response_data):
"""Parse API response with various timestamp formats"""
results = {}
# Handle different timestamp formats
if 'timestamp' in response_data:
ts = response_data['timestamp']
# Detect if milliseconds (roughly > year 2001 in ms)
if ts > 1000000000000:
results['datetime'] = datetime.fromtimestamp(ts / 1000)
results['format'] = 'milliseconds'
else:
results['datetime'] = datetime.fromtimestamp(ts)
results['format'] = 'seconds'
if 'iso_timestamp' in response_data:
iso_str = response_data['iso_timestamp']
# Parse ISO format (basic parsing)
if iso_str.endswith('Z'):
iso_str = iso_str[:-1] + '+00:00'
results['iso_datetime'] = datetime.fromisoformat(iso_str)
return results
# Example API data
api_data = prepare_api_data({"sensor_id": "temp_01", "value": 23.5})
print("API Data:")
print(json.dumps(api_data, indent=2))
# Example parsing
response = {
'timestamp': 1710519045123, # milliseconds
'iso_timestamp': '2024-03-15T14:30:45Z',
'status': 'success'
}
parsed = parse_api_response(response)
print("\nParsed Response:")
for key, value in parsed.items():
print(f"{key}: {value}")
🎯 Key Takeaways
🚀 What's Next?
Congratulations! You've mastered Python's date and time operations. Now you're ready to tackle error handling and debugging techniques.
Continue to: Error Handling to learn how to make your code robust and maintainable.
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.