Esta página está disponible temporalmente en inglés. La traducción al español está en preparación.
Introduction
Python provides two main modules for working with dates and timestamps: datetime for high-level date operations and time for lower-level timestamp operations. Understanding how to properly use timestamps in Python is essential for data processing, API integration, and time-based applications. This guide covers timestamp fundamentals, conversions, timezone handling, and best practices.
Getting Current Timestamp
Using time Module
PYTHON1import time 2 3# Get current Unix timestamp (seconds since epoch) 4now_seconds = time.time() 5print(now_seconds) # e.g., 1704672000.123456 6 7# Get current timestamp as integer 8now_int = int(time.time()) 9print(now_int) # e.g., 1704672000 10 11# Get current time in milliseconds 12now_ms = int(time.time() * 1000) 13print(now_ms) # e.g., 1704672000123
Using datetime Module
PYTHON1from datetime import datetime 2 3# Get current UTC datetime 4now_utc = datetime.utcnow() 5print(now_utc) # 2024-01-08 00:00:00.123456 6 7# Get current local datetime 8now_local = datetime.now() 9print(now_local) # 2024-01-07 19:00:00.123456 (if EST) 10 11# Get timestamp from datetime 12timestamp = now_utc.timestamp() 13print(timestamp) # e.g., 1704672000.123456
Best Practice: Use
datetime.utcnow()for UTC timestamps anddatetime.now()for local timestamps. Always be explicit about timezone.
Creating Datetime from Timestamp
From Unix Timestamp (Seconds)
PYTHON1from datetime import datetime 2 3# Create datetime from Unix timestamp (seconds) 4dt = datetime.fromtimestamp(1704672000) 5print(dt) # 2024-01-07 19:00:00 (local timezone) 6 7# Create UTC datetime from Unix timestamp 8dt_utc = datetime.utcfromtimestamp(1704672000) 9print(dt_utc) # 2024-01-08 00:00:00+00:00 (UTC)
From Unix Timestamp (Milliseconds)
PYTHON1from datetime import datetime 2 3# Convert milliseconds to datetime 4ts_ms = 1704672000123 5dt = datetime.fromtimestamp(ts_ms / 1000) 6print(dt) # 2024-01-08 00:00:00.123000
Important:
datetime.fromtimestamp()uses local timezone. Usedatetime.utcfromtimestamp()for UTC.
From Date Components
PYTHON1from datetime import datetime 2 3# Create from year, month, day, hour, minute, second 4dt = datetime(2024, 1, 8, 14, 30, 45) 5print(dt) # 2024-01-08 14:30:45 6 7# Create date only (time defaults to midnight) 8dt_date = datetime(2024, 1, 8) 9print(dt_date) # 2024-01-08 00:00:00 10 11# Create time only (date defaults to 1900-01-01) 12from datetime import time 13t = time(14, 30, 45) 14print(t) # 14:30:45
Python Range: datetime objects can represent years 1 to 9999.
Converting Datetime to Timestamp
Using timestamp() Method
PYTHON1from datetime import datetime 2 3# Convert datetime to Unix timestamp (seconds) 4dt = datetime(2024, 1, 8, 14, 30, 45) 5timestamp = dt.timestamp() 6print(timestamp) # e.g., 1704672654.0 7 8# Convert UTC datetime to timestamp 9dt_utc = datetime(2024, 1, 8, 14, 30, 45, tzinfo=timezone.utc) 10timestamp_utc = dt_utc.timestamp() 11print(timestamp_utc) # e.g., 1704695045.0
Using calendar.timegm() for UTC
PYTHON1import calendar 2from datetime import datetime 3 4# Convert UTC datetime to timestamp (naive datetime assumed UTC) 5dt = datetime(2024, 1, 8, 14, 30, 45) 6timestamp_utc = calendar.timegm(dt.timetuple()) 7print(timestamp_utc) # e.g., 1704695045 8 9# More reliable than timestamp() for UTC naive datetimes
Use Case:
calendar.timegm()is useful when working with UTC timestamps from naive datetimes.
Date Arithmetic
Adding and Subtracting Time
PYTHON1from datetime import datetime, timedelta 2 3# Add 7 days 4dt = datetime(2024, 1, 8) 5future = dt + timedelta(days=7) 6print(future) # 2024-01-15 00:00:00 7 8# Subtract 1 hour 9past = dt - timedelta(hours=1) 10print(past) # 2024-01-07 23:00:00 11 12# Add 2 hours and 30 minutes 13dt = datetime(2024, 1, 8, 10, 0, 0) 14dt = dt + timedelta(hours=2, minutes=30) 15print(dt) # 2024-01-08 12:30:00 16 17# Add negative timedelta (subtract) 18dt = datetime(2024, 1, 8) 19dt = dt + timedelta(days=-1) 20print(dt) # 2024-01-07 00:00:00
Calculating Duration
PYTHON1from datetime import datetime 2 3# Calculate duration between two datetimes 4dt1 = datetime(2024, 1, 8, 10, 0, 0) 5dt2 = datetime(2024, 1, 8, 18, 0, 0) 6 7duration = dt2 - dt1 8print(duration) # 8:00:00 9 10# Extract duration components 11print(duration.days) # 0 12print(duration.seconds) # 28800 (8 hours) 13print(duration.total_seconds()) # 28800.0 14 15# Calculate in hours 16hours = duration.total_seconds() / 3600 17print(f"Duration: {hours} hours") # Duration: 8.0 hours
Business Days Calculation
PYTHON1from datetime import datetime, timedelta 2 3def add_business_days(start_date, days): 4 """Add business days to a date (excludes weekends)""" 5 result = start_date 6 added_days = 0 7 8 while added_days < days: 9 result += timedelta(days=1) 10 if result.weekday() < 5: # Monday=0, Friday=4 11 added_days += 1 12 13 return result 14 15# Example 16start = datetime(2024, 1, 8) 17result = add_business_days(start, 5) 18print(result) # 2024-01-15 (Monday)
Recommendation: Use the
python-dateutillibrary for more advanced business day calculations including holidays.
Formatting Dates
ISO 8601 Format
PYTHON1from datetime import datetime 2 3# Format as ISO 8601 4dt = datetime(2024, 1, 8, 14, 30, 45) 5iso_string = dt.isoformat() 6print(iso_string) # 2024-01-08T14:30:45 7 8# With timezone (using pytz) 9import pytz 10tz = pytz.timezone('America/New_York') 11dt = datetime(2024, 1, 8, 14, 30, 45, tzinfo=tz) 12iso_with_tz = dt.isoformat() 13print(iso_with_tz) # 2024-01-08T14:30:45-05:00
Custom Formatting with strftime
PYTHON1from datetime import datetime 2 3dt = datetime(2024, 1, 8, 14, 30, 45) 4 5# Common format codes 6formats = { 7 'YYYY-MM-DD': dt.strftime('%Y-%m-%d'), # 2024-01-08 8 'YYYY/MM/DD HH:MM': dt.strftime('%Y/%m/%d %H:%M'), # 2024/01/08 14:30 9 'Day Month, Year': dt.strftime('%d %B, %Y'), # 08 January, 2024 10 'Weekday': dt.strftime('%A'), # Monday 11 'Short Weekday': dt.strftime('%a'), # Mon 12 'Time': dt.strftime('%H:%M:%S'), # 14:30:45 13 'AM/PM': dt.strftime('%I:%M %p'), # 02:30 PM 14} 15 16for name, formatted in formats.items(): 17 print(f"{name}: {formatted}")
Format Codes:
TEXT1%Y Year (4 digits) %m Month (01-12) 2%y Year (2 digits) %d Day (01-31) 3%B Month name (January) %b Month abbr (Jan) 4%A Weekday name (Monday) %a Weekday abbr (Mon) 5%H Hour (00-23) %I Hour (01-12) 6%M Minute (00-59) %S Second (00-59) 7%p AM/PM %f Microseconds (000000-999999)
Format for Different Locales
PYTHON1from datetime import datetime 2import locale 3 4dt = datetime(2024, 1, 8, 14, 30, 45) 5 6# Set locale 7locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') 8en_format = dt.strftime('%B %d, %Y') # January 08, 2024 9 10locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8') 11fr_format = dt.strftime('%d %B %Y') # 08 janvier 2024 12 13locale.setlocale(locale.LC_ALL, 'zh_CN.UTF-8') 14zh_format = dt.strftime('%Y年%m月%d日') # 2024年01月08日
Note:
locale.setlocale()affects the entire process. Uselocale.getlocale()to restore original locale.
Parsing Dates
Parsing ISO 8601 Strings
PYTHON1from datetime import datetime 2 3# Parse ISO 8601 string 4iso_string = "2024-01-08T14:30:45" 5dt = datetime.fromisoformat(iso_string) 6print(dt) # 2024-01-08 14:30:45 7 8# Parse with timezone 9iso_tz_string = "2024-01-08T14:30:45-05:00" 10dt_tz = datetime.fromisoformat(iso_tz_string) 11print(dt_tz) # 2024-01-08 14:30:45-05:00
Parsing Custom Formats with strptime
PYTHON1from datetime import datetime 2 3# Parse custom format 4date_string = "08 January, 2024 14:30:45" 5dt = datetime.strptime(date_string, '%d %B, %Y %H:%M:%S') 6print(dt) # 2024-01-08 14:30:45 7 8# Parse US format 9us_string = "01/08/2024 2:30 PM" 10dt_us = datetime.strptime(us_string, '%m/%d/%Y %I:%M %p') 11print(dt_us) # 2024-01-08 14:30:00 12 13# Parse 24-hour format 14eu_string = "08.01.2024 14:30" 15dt_eu = datetime.strptime(eu_string, '%d.%m.%Y %H:%M') 16print(dt_eu) # 2024-01-08 14:30:00
Format Codes for strptime:
TEXT1Same as strftime() format codes: 2 %Y (year), %m (month), %d (day) 3 %H (hour 24), %I (hour 12), %M (minute), %S (second) 4 %p (AM/PM), %f (microseconds) 5 %B (month name), %A (weekday name)
Handling Parse Errors
PYTHON1from datetime import datetime 2 3def safe_parse_date(date_string, format_string): 4 """Parse date string with error handling""" 5 try: 6 return datetime.strptime(date_string, format_string) 7 except ValueError as e: 8 print(f"Failed to parse date: {date_string}") 9 print(f"Error: {e}") 10 return None 11 12# Examples 13valid = safe_parse_date("2024-01-08", "%Y-%m-%d") 14invalid = safe_parse_date("invalid date", "%Y-%m-%d") 15 16print(valid) # 2024-01-08 00:00:00 17print(invalid) # Failed to parse date: invalid date
Timezone Handling
Using pytz Library
PYTHON1from datetime import datetime 2import pytz 3 4# Create datetime with timezone 5tz = pytz.timezone('America/New_York') 6dt_aware = datetime(2024, 1, 8, 14, 30, 45, tzinfo=tz) 7print(dt_aware) # 2024-01-08 14:30:45-05:00 8 9# Convert between timezones 10tokyo_tz = pytz.timezone('Asia/Tokyo') 11dt_tokyo = dt_aware.astimezone(tokyo_tz) 12print(dt_tokyo) # 2024-01-09 04:30:45+09:00 13 14# Get current time in specific timezone 15tz = pytz.timezone('Europe/London') 16now_london = datetime.now(tz) 17print(now_london) # 2024-01-08 00:00:00+00:00
Best Practice: Install pytz with
pip install pytzfor comprehensive timezone support.
Using zoneinfo (Python 3.9+)
PYTHON1from datetime import datetime, timezone 2from zoneinfo import ZoneInfo 3 4# Python 3.9+ built-in timezone support 5tz = ZoneInfo('America/New_York') 6dt_aware = datetime(2024, 1, 8, 14, 30, 45, tzinfo=tz) 7print(dt_aware) # 2024-01-08 14:30:45-05:00 8 9# Convert to UTC 10dt_utc = dt_aware.astimezone(timezone.utc) 11print(dt_utc) # 2024-01-08 19:30:45+00:00
Advantage:
zoneinfois built into Python 3.9+, no external dependencies needed.
UTC vs Local Time
PYTHON1from datetime import datetime 2 3# Get local time (system timezone) 4dt_local = datetime.now() 5print(f"Local: {dt_local}") 6 7# Get UTC time 8dt_utc = datetime.utcnow() 9print(f"UTC: {dt_utc}") 10 11# Convert local to UTC (requires timezone-aware datetime) 12import pytz 13tz = pytz.timezone('America/New_York') 14dt_aware = datetime.now(tz) 15dt_utc = dt_aware.astimezone(pytz.utc) 16print(f"Converted to UTC: {dt_utc}")
Common Operations
Start/End of Period
PYTHON1from datetime import datetime, timedelta 2 3def start_of_day(dt): 4 """Return start of day (midnight)""" 5 return dt.replace(hour=0, minute=0, second=0, microsecond=0) 6 7def end_of_day(dt): 8 """Return end of day (23:59:59.999999)""" 9 return dt.replace(hour=23, minute=59, second=59, microsecond=999999) 10 11def start_of_month(dt): 12 """Return start of month""" 13 return dt.replace(day=1, hour=0, minute=0, second=0, microsecond=0) 14 15def end_of_month(dt): 16 """Return end of month""" 17 if dt.month == 12: 18 return dt.replace(year=dt.year + 1, month=1, day=1) - timedelta(days=1) 19 return dt.replace(month=dt.month + 1, day=1) - timedelta(days=1) 20 21# Examples 22dt = datetime(2024, 1, 15, 14, 30, 45) 23print(start_of_day(dt)) # 2024-01-15 00:00:00 24print(end_of_month(dt)) # 2024-01-31 23:59:59.999999
Age Calculation
PYTHON1from datetime import datetime 2 3def calculate_age(birth_date): 4 """Calculate age in years, months, and days""" 5 today = datetime.now() 6 birth = datetime.fromisoformat(birth_date) 7 8 years = today.year - birth.year 9 months = today.month - birth.month 10 days = today.day - birth.day 11 12 # Adjust if birthday hasn't happened yet this year 13 if (months < 0 or (months == 0 and days < 0)): 14 years -= 1 15 months += 12 16 17 return { 18 'years': years, 19 'months': months, 20 'days': days 21 } 22 23# Example 24age = calculate_age('1990-06-15') 25print(f"Age: {age['years']} years, {age['months']} months, {age['days']} days") 26# Age: 33 years, 6 months, -7 days
Countdown Timer
PYTHON1from datetime import datetime 2 3def countdown(target_date_str): 4 """Calculate countdown to target date""" 5 target = datetime.fromisoformat(target_date_str) 6 now = datetime.now() 7 diff = target - now 8 9 if diff.total_seconds() <= 0: 10 return {'expired': True, 'text': 'Target date passed'} 11 12 days = diff.days 13 hours = diff.seconds // 3600 14 minutes = (diff.seconds % 3600) // 60 15 seconds = diff.seconds % 60 16 17 return { 18 'expired': False, 19 'text': f"{days} days, {hours} hours, {minutes} minutes, {seconds} seconds", 20 'total_seconds': diff.total_seconds() 21 } 22 23# Example 24result = countdown('2024-12-31T00:00:00') 25print(result['text']) 26# "357 days, 11 hours, 29 minutes, 12 seconds"
Best Practices
Timezone Best Practices
TEXT1✅ Always store UTC timestamps in databases 2✅ Convert to local timezone only for display 3✅ Use timezone-aware datetime objects for user-facing times 4✅ Document timezone assumptions in code comments 5✅ Use IANA timezone names (America/New_York, not UTC-5) 6❌ Don't store local timestamps without timezone metadata 7❌ Don't mix UTC and naive datetimes in calculations 8❌ Don't assume server timezone matches user timezone 9❌ Don't use pytz for Python 3.9+ (use zoneinfo instead)
Performance Tips
TEXT1✅ Use datetime.timestamp() instead of time.time() for datetime objects 2✅ Cache timezone objects when used repeatedly 3✅ Use datetime.utcnow() for UTC (faster than aware datetimes) 4✅ Use timedelta arithmetic for time calculations (more readable) 5❌ Don't create timezone objects in loops (reuse them) 6❌ Don't call datetime.now() in tight loops (call once and reuse)
Data Integrity
PYTHON1from datetime import datetime 2 3def validate_datetime(dt): 4 """Validate datetime object is within reasonable range""" 5 if not isinstance(dt, datetime): 6 return False, "Not a datetime object" 7 8 if dt.year < 1900 or dt.year > 2100: 9 return False, "Year out of reasonable range" 10 11 if dt.month < 1 or dt.month > 12: 12 return False, "Invalid month" 13 14 if dt.day < 1 or dt.day > 31: 15 return False, "Invalid day" 16 17 return True, "Valid" 18 19# Example 20valid = validate_datetime(datetime(2024, 1, 8, 14, 30, 45)) 21print(valid) # (True, "Valid") 22 23invalid = validate_datetime(datetime(2024, 13, 1)) 24print(invalid) # (False, "Invalid month")
Related Tools
- Unix Timestamp Converter - Convert Unix timestamps to dates
- Current Timestamp - Get current timestamp in multiple formats
- Timestamp Format Converter - Convert between timestamp formats
- UTC/Local Converter - Convert between UTC and local time
- Timestamp Validator - Validate timestamp formats and ranges
Additional Resources
- Python datetime Documentation↗
- Python time Module↗
- pytz Library↗
- Python zoneinfo (Python 3.9+)↗
- dateutil Library↗
For production applications with complex timezone or business day requirements, consider using:
- pytz: Legacy but widely supported timezone library
- zoneinfo: Built-in Python 3.9+ (preferred for new code)
- python-dateutil: Advanced date parsing and business day calculations
- pendulum: Pythonic datetime library with better timezone handling
Python's
datetimemodule is sufficient for basic operations, but libraries provide better timezone support and parsing for complex use cases.