Skip to main content

Official Documentation & Resources

Primary Official Sources (REQUIRED)

Additional Authoritative Sources

IMPORTANT: Examples in this guide are adapted from the official Python documentation at https://docs.python.org/3/library/datetime.html

Overview

The time class represents an idealized time, independent of any particular day, assuming that every day has exactly 246060 seconds. Time objects are immutable and hashable. A time object can be timezone-aware or timezone-naive.

Attributes: hour, minute, second, microsecond, and tzinfo.

Key Characteristics

  • Immutable Objects: Time objects cannot be modified after creation
  • Thread Safety: Time objects are immutable and therefore thread-safe
  • Timezone Support: Can be timezone-naive or timezone-aware
  • Microsecond Precision: Supports microsecond precision (6 decimal places)
  • 24-hour Format: Hours range from 0 to 23
  • Hashable: Can be used as dictionary keys and in sets

Prerequisites and Setup

Python Version Compatibility

  • Minimum Python version required: Python 2.3+ (datetime module introduction)
  • Timezone support: Python 3.2+ (timezone class)

Installation and Imports

# Standard library (no installation needed)
from datetime import time, timezone

# Alternative import
import datetime
# Then use: datetime.time()

Basic Usage

Official Documentation Examples

Source: All examples adapted from https://docs.python.org/3/library/datetime.html#time-objects

Simple Example

from datetime import time

# Creating specific times (from official docs)
t = time(14, 30, 0) # 2:30 PM
print(f"Time: {t}") # Time: 14:30:00

# Time with microseconds (from official docs)
precise_time = time(14, 30, 0, 123456)
print(f"Precise time: {precise_time}") # Precise time: 14:30:00.123456

# Time formatting (from official docs)
print(t.strftime("%I:%M %p")) # 02:30 PM

Core Methods/Functions

from datetime import time

# Constructor (from official docs)
t = time(14, 30, 45)
print(t) # 14:30:45

# ISO format (from official docs)
iso_time = t.isoformat()
print(f"ISO format: {iso_time}") # ISO format: 14:30:45

# Custom formatting (from official docs)
formatted = t.strftime("%H:%M:%S")
print(f"Formatted: {formatted}") # Formatted: 14:30:45

Common Patterns

# Pattern 1: Basic usage (from official docs)
from datetime import time

t = time(14, 30, 45, 123456)
print(f"Hour: {t.hour}, Minute: {t.minute}, Second: {t.second}")

# Pattern 2: Time parsing (from official docs)
iso_string = "14:30:45"
parsed_time = time.fromisoformat(iso_string)
print(f"Parsed: {parsed_time}")

# Pattern 3: Error handling (from official docs)
try:
invalid_time = time(25, 0, 0) # Invalid hour
except ValueError as e:
print(f"Error: {e}") # Error: hour must be in 0..23

time API Reference

Constructor

MethodDescriptionParametersReturn TypeExample
time(hour, minute, second, microsecond, tzinfo)Create a time objectAll optional, defaults to 0 except tzinfotimetime(14, 30, 0)

Class Methods

MethodDescriptionReturn TypeExample
fromisoformat(time_string)Parse ISO 8601 time stringtimetime.fromisoformat('14:30:00')

Instance Methods

MethodDescriptionReturn TypeExample
strftime(format)Format as stringstrt.strftime('%H:%M:%S')
isoformat(timespec='auto')ISO 8601 formatstrt.isoformat()
replace(**kwargs)Return time with new valuestimet.replace(hour=15)
utcoffset()UTC offset (if timezone-aware)timedelta or Nonet.utcoffset()
dst()Daylight saving time offsettimedelta or Nonet.dst()
tzname()Timezone namestr or Nonet.tzname()

Properties and Attributes

AttributeDescriptionTypeRangeExample
hourHourint0-23t.hour
minuteMinuteint0-59t.minute
secondSecondint0-59t.second
microsecondMicrosecondint0-999999t.microsecond
tzinfoTimezone infotzinfo or None-t.tzinfo

Detailed Method Examples

Creating time Objects (from official docs)

from datetime import time, timezone

# Basic creation (from official docs)
t = time(14, 30, 45)
print(t) # 14:30:45

# With microseconds (from official docs)
precise = time(14, 30, 45, 123456)
print(precise) # 14:30:45.123456

# With timezone (from official docs)
utc_time = time(14, 30, 45, tzinfo=timezone.utc)
print(utc_time) # 14:30:45+00:00

# From ISO format (from official docs)
iso_time = time.fromisoformat('14:30:45')
print(f"From ISO: {iso_time}")

Time Formatting (from official docs)

from datetime import time

t = time(14, 30, 45, 123456)

# ISO format (from official docs)
print(t.isoformat()) # 14:30:45.123456

# Different timespec options (from official docs)
print(t.isoformat(timespec='hours')) # 14
print(t.isoformat(timespec='minutes')) # 14:30
print(t.isoformat(timespec='seconds')) # 14:30:45
print(t.isoformat(timespec='milliseconds')) # 14:30:45.123
print(t.isoformat(timespec='microseconds')) # 14:30:45.123456

# Custom formatting (from official docs)
print(t.strftime("%I:%M:%S %p")) # 02:30:45 PM
print(t.strftime("%H:%M")) # 14:30
print(t.strftime("%H.%M.%S")) # 14.30.45

Time Properties (from official docs)

from datetime import time

t = time(14, 30, 45, 123456)

# Basic properties (from official docs)
print(f"Hour: {t.hour}") # Hour: 14
print(f"Minute: {t.minute}") # Minute: 30
print(f"Second: {t.second}") # Second: 45
print(f"Microsecond: {t.microsecond}") # Microsecond: 123456
print(f"Timezone: {t.tzinfo}") # Timezone: None

Time Replacement (from official docs)

from datetime import time

t = time(14, 30, 45)

# Replace specific components (from official docs)
new_hour = t.replace(hour=16)
print(f"New hour: {new_hour}") # New hour: 16:30:45

new_minute = t.replace(minute=0)
print(f"New minute: {new_minute}") # New minute: 14:00:45

# Multiple replacements (from official docs)
new_time = t.replace(hour=9, minute=15, second=0)
print(f"New time: {new_time}") # New time: 09:15:00

Timezone-Aware Times (from official docs)

from datetime import time, timezone, timedelta

# UTC time (from official docs)
utc_time = time(14, 30, 45, tzinfo=timezone.utc)
print(f"UTC time: {utc_time}") # UTC time: 14:30:45+00:00

# Custom timezone (from official docs)
est = timezone(timedelta(hours=-5))
est_time = time(9, 30, 45, tzinfo=est)
print(f"EST time: {est_time}") # EST time: 09:30:45-05:00

# Timezone methods (from official docs)
print(f"UTC offset: {utc_time.utcoffset()}") # UTC offset: 0:00:00
print(f"Timezone name: {utc_time.tzname()}") # Timezone name: UTC
print(f"DST: {utc_time.dst()}") # DST: None

Time Comparison (from official docs)

from datetime import time

t1 = time(14, 30, 45)
t2 = time(15, 30, 45)
t3 = time(14, 30, 45)

# Comparison operations (from official docs)
print(f"t1 < t2: {t1 < t2}") # t1 < t2: True
print(f"t1 == t3: {t1 == t3}") # t1 == t3: True
print(f"t1 > t2: {t1 > t2}") # t1 > t2: False

# Sorting times (from official docs)
times = [time(16, 0), time(9, 30), time(14, 15)]
sorted_times = sorted(times)
print(f"Sorted: {sorted_times}") # Sorted: [09:30:00, 14:15:00, 16:00:00]

Important Notes

Gotchas and Common Pitfalls

  • Time objects are immutable - methods return new objects
  • Cannot perform arithmetic operations on time objects (use datetime instead)
  • Timezone-naive and timezone-aware times cannot be compared
  • Time objects represent time of day, not duration

Error Handling

from datetime import time

# Invalid time handling (from official docs)
try:
invalid = time(25, 0, 0) # Hour out of range
except ValueError as e:
print(f"Error: {e}")

try:
invalid = time(14, 60, 0) # Minute out of range
except ValueError as e:
print(f"Error: {e}")

try:
invalid = time(14, 30, 60) # Second out of range
except ValueError as e:
print(f"Error: {e}")

Performance Considerations

  • Time objects are lightweight and efficient
  • Immutability makes them safe for use as dictionary keys
  • Timezone-aware times require additional computation

Best Practices

  1. Use ISO format for string representation - Use isoformat() for consistent formatting
  2. Handle ValueError exceptions - Invalid times will raise ValueError
  3. Be consistent with timezone awareness - Don't mix naive and aware times
  4. Use replace() for time modifications - Returns new object with specified changes
  5. Consider precision needs - Use microseconds only when necessary
  6. Use datetime for arithmetic - Time objects don't support arithmetic operations
  • datetime.date - Date without time information
  • datetime.datetime - Combined date and time
  • datetime.timezone - Timezone information
  • datetime.tzinfo - Abstract timezone base class
  • Main datetime module - Complete module overview