Date & Time
Time Introduction
Scheduling systems and time tracking applications need to work with times of day independent of dates. Python's time class represents hours, minutes, seconds, and microseconds. Learn to create times, access components, and validate business hours for real-world applications.
Combining with Dates
create.py
# Create specific time
from datetime import time
# Create specific times
# Create with hour and minute
time1 =
print(f"Time 1 (HH:MM): {time1}")
# Create with hour, minute, second
time2 = time(14, 30, 45)
print(f"Time 2 (HH:MM:SS): {time2}")
# Create with hour, minute, second, microsecond
time3 = time(14, 30, 45, 123456)
print(f"Time 3 (with micros): {time3}")
# Common times
morning = time(9, 0)
lunch_time = time(12, 30)
evening = time(18, 0)
print("\nCommon times:")
print(f"Morning: {morning}")
print(f"Lunch: {lunch_time}")
print(f"Evening: {evening}")
# Midnight
midnight = time(0, 0, 0)
# or
midnight2 = time.min
print(f"\nMidnight: {midnight}")
print(f"Midnight (min): {midnight2}")
# Almost midnight
almost_midnight = time(23, 59, 59, 999999)
# or
almost_midnight2 = time.max
print(f"Almost midnight: {almost_midnight}")
print(f"Almost midnight (max): {almost_midnight2}")
# Modify components
modified = time1.replace(hour=16, minute=45)
print(f"\nModified: {modified}")
# Only change hour
next_hour = time1.replace(hour=time1.hour + 1)
print(f"Next hour: {next_hour}")
# Min and max
min_time = time.min
max_time = time.max
print(f"\nMin: {min_time}")
print(f"Max: {max_time}")
# Noon
noon = time(12, 0)
print(f"Noon: {noon}")
# Generate hourly times
print("\nHourly times (9-17):")
for hour in range(9, 18):
t = time(hour, 0)
print(f" {t}")
# Quarter hours
print("\nQuarter hours:")
for minute in [0, 15, 30, 45]:
t = time(14, minute)
print(f" {t}")
# Create specific time
from datetime import time
# Create specific times
# Create with hour and minute
time1 =
print(f"Time 1 (HH:MM): {time1}")
# Create with hour, minute, second
time2 = time(14, 30, 45)
print(f"Time 2 (HH:MM:SS): {time2}")
# Create with hour, minute, second, microsecond
time3 = time(14, 30, 45, 123456)
print(f"Time 3 (with micros): {time3}")
# Common times
morning = time(9, 0)
lunch_time = time(12, 30)
evening = time(18, 0)
print("\nCommon times:")
print(f"Morning: {morning}")
print(f"Lunch: {lunch_time}")
print(f"Evening: {evening}")
# Midnight
midnight = time(0, 0, 0)
# or
midnight2 = time.min
print(f"\nMidnight: {midnight}")
print(f"Midnight (min): {midnight2}")
# Almost midnight
almost_midnight = time(23, 59, 59, 999999)
# or
almost_midnight2 = time.max
print(f"Almost midnight: {almost_midnight}")
print(f"Almost midnight (max): {almost_midnight2}")
# Modify components
modified = time1.replace(hour=16, minute=45)
print(f"\nModified: {modified}")
# Only change hour
next_hour = time1.replace(hour=time1.hour + 1)
print(f"Next hour: {next_hour}")
# Min and max
min_time = time.min
max_time = time.max
print(f"\nMin: {min_time}")
print(f"Max: {max_time}")
# Noon
noon = time(12, 0)
print(f"Noon: {noon}")
# Generate hourly times
print("\nHourly times (9-17):")
for hour in range(9, 18):
t = time(hour, 0)
print(f" {t}")
# Quarter hours
print("\nQuarter hours:")
for minute in [0, 15, 30, 45]:
t = time(14, minute)
print(f" {t}")
# Create specific time
from datetime import time
# Create specific times
# Create with hour and minute
time1 =
print(f"Time 1 (HH:MM): {time1}")
# Create with hour, minute, second
time2 = time(14, 30, 45)
print(f"Time 2 (HH:MM:SS): {time2}")
# Create with hour, minute, second, microsecond
time3 = time(14, 30, 45, 123456)
print(f"Time 3 (with micros): {time3}")
# Common times
morning = time(9, 0)
lunch_time = time(12, 30)
evening = time(18, 0)
print("\nCommon times:")
print(f"Morning: {morning}")
print(f"Lunch: {lunch_time}")
print(f"Evening: {evening}")
# Midnight
midnight = time(0, 0, 0)
# or
midnight2 = time.min
print(f"\nMidnight: {midnight}")
print(f"Midnight (min): {midnight2}")
# Almost midnight
almost_midnight = time(23, 59, 59, 999999)
# or
almost_midnight2 = time.max
print(f"Almost midnight: {almost_midnight}")
print(f"Almost midnight (max): {almost_midnight2}")
# Modify components
modified = time1.replace(hour=16, minute=45)
print(f"\nModified: {modified}")
# Only change hour
next_hour = time1.replace(hour=time1.hour + 1)
print(f"Next hour: {next_hour}")
# Min and max
min_time = time.min
max_time = time.max
print(f"\nMin: {min_time}")
print(f"Max: {max_time}")
# Noon
noon = time(12, 0)
print(f"Noon: {noon}")
# Generate hourly times
print("\nHourly times (9-17):")
for hour in range(9, 18):
t = time(hour, 0)
print(f" {t}")
# Quarter hours
print("\nQuarter hours:")
for minute in [0, 15, 30, 45]:
t = time(14, minute)
print(f" {t}")
current.py
# Current time
from datetime import datetime, time
# Get current time
# Current time (from datetime)
now = datetime.now().time()
print(f"Now: {now}")
# Time components
hour = now.hour
minute = now.minute
second = now.second
microsecond = now.microsecond
print("\nTime components:")
print(f"Hour: {hour}")
print(f"Minute: {minute}")
print(f"Second: {second}")
print(f"Microsecond: {microsecond}")
# Formatted output
print(f"\nFormatted: {hour:02d}:{minute:02d}:{second:02d}")
# 12-hour format
hour12 = hour % 12
if hour12 == 0:
hour12 = 12
am_pm = "AM" if hour < 12 else "PM"
print(f"12-hour: {hour12:02d}:{minute:02d} {am_pm}")
# Truncated times
to_minute = now.replace(second=0, microsecond=0)
print(f"\nTruncated to minute: {to_minute}")
to_second = now.replace(microsecond=0)
print(f"Truncated to second: {to_second}")
# Special times
midnight = time.min # 00:00:00
almost_midnight = time.max # 23:59:59.999999
print("\nSpecial times:")
print(f"Midnight (min): {midnight}")
print(f"Almost midnight (max): {almost_midnight}")
# ISO format
iso = now.isoformat()
print(f"\nISO format: {iso}")
# With milliseconds
millis = now.microsecond // 1000
print(f"Milliseconds: {millis}")
# String representation
print(f"\nString repr: {repr(now)}")
print(f"String str: {str(now)}")
components.py
# Time components
from datetime import time
# Extract time components
t = time(14, 30, 45, 123456)
print(f"Time: {t}")
print()
# Hour, minute, second
print(f"Hour: {t.hour}")
print(f"Minute: {t.minute}")
print(f"Second: {t.second}")
print(f"Microsecond: {t.microsecond}")
# Tzinfo (timezone info, if any)
print(f"Timezone: {t.tzinfo}")
# Calculate milliseconds
millis = t.microsecond // 1000
print(f"\nMilliseconds: {millis}")
# 12-hour format components
hour24 = t.hour
hour12 = hour24 % 12
if hour12 == 0:
hour12 = 12
am_pm = "AM" if hour24 < 12 else "PM"
print(f"\n12-hour format:")
print(f"Hour (12): {hour12}")
print(f"AM/PM: {am_pm}")
print(f"Time: {hour12}:{t.minute:02d} {am_pm}")
# Truncate precision
to_minute = t.replace(second=0, microsecond=0)
to_second = t.replace(microsecond=0)
print(f"\nTruncated:")
print(f"Original: {t}")
print(f"To minute: {to_minute}")
print(f"To second: {to_second}")
# ISO format
iso = t.isoformat()
print(f"\nISO format: {iso}")
# String formatting
print(f"\nFormatted:")
print(f" HH:MM:SS - {t.hour:02d}:{t.minute:02d}:{t.second:02d}")
print(f" HH:MM - {t.hour:02d}:{t.minute:02d}")
# Time period
print(f"\nTime period:")
if t.hour < 12:
print("Morning")
elif t.hour < 17:
print("Afternoon")
elif t.hour < 21:
print("Evening")
else:
print("Night")
# Display various times
print("\nVarious times of day:")
times = [
time(6, 0),
time(12, 0),
time(18, 0),
time(23, 59)
]
for time_obj in times:
print(f"{time_obj} - {time_obj.hour}h {time_obj.minute}m")
# Resolution
resolution = time.resolution
print(f"\nTime resolution: {resolution}")
compare.py
# Compare times
from datetime import time
# Compare times
time1 = time(9, 30)
time2 = time(14, 45)
time3 = time(9, 30)
print(f"Time 1: {time1}")
print(f"Time 2: {time2}")
print(f"Time 3: {time3}")
print()
# Comparison operators
print(f"time1 < time2: {time1 < time2}")
print(f"time1 > time2: {time1 > time2}")
print(f"time1 <= time2: {time1 <= time2}")
print(f"time1 >= time2: {time1 >= time2}")
# Equality
print(f"\ntime1 == time2: {time1 == time2}")
print(f"time1 == time3: {time1 == time3}")
print(f"time1 != time2: {time1 != time2}")
# Find min/max
times_list = [time1, time2, time3]
earliest = min(times_list)
latest = max(times_list)
print(f"\nEarliest: {earliest}")
print(f"Latest: {latest}")
# Check if in time range
check =
start = time(9, 0)
end = time(17, 0)
in_range = start <= check <= end
print(f"\n{check} in range [{start}, {end}]: {in_range}")
# Sort times
unsorted = [
time(15, 30),
time(9, 0),
time(12, 15)
]
print("\nBefore sort:")
for t in unsorted:
print(f" {t}")
sorted_times = sorted(unsorted)
print("After sort:")
for t in sorted_times:
print(f" {t}")
# Business hours check
business_start = time(9, 0)
business_end = time(17, 0)
print("\nBusiness hours check:")
test_times = [
time(8, 30),
time(12, 0),
time(18, 0)
]
for t in test_times:
is_during_business = business_start <= t < business_end
print(f"{t} during business: {is_during_business}")
# Midnight crossing
late = time(23, 0)
early = time(1, 0)
print(f"\n23:00 < 01:00: {late < early}") # True (earlier in day)
# Special time comparisons
print("\nSpecial comparisons:")
print(f"Midnight: {time.min}")
print(f"Almost midnight: {time.max}")
print(f"Noon: {time(12, 0)}")
noon = time(12, 0)
print(f"10:00 < noon: {time(10, 0) < noon}")
print(f"14:00 > noon: {time(14, 0) > noon}")
# Filter times
all_times = [
time(8, 0),
time(10, 0),
time(14, 0),
time(18, 0)
]
morning_times = [t for t in all_times if t < time(12, 0)]
afternoon_times = [t for t in all_times if t >= time(12, 0)]
print(f"\nMorning times: {morning_times}")
print(f"Afternoon times: {afternoon_times}")
# Compare times
from datetime import time
# Compare times
time1 = time(9, 30)
time2 = time(14, 45)
time3 = time(9, 30)
print(f"Time 1: {time1}")
print(f"Time 2: {time2}")
print(f"Time 3: {time3}")
print()
# Comparison operators
print(f"time1 < time2: {time1 < time2}")
print(f"time1 > time2: {time1 > time2}")
print(f"time1 <= time2: {time1 <= time2}")
print(f"time1 >= time2: {time1 >= time2}")
# Equality
print(f"\ntime1 == time2: {time1 == time2}")
print(f"time1 == time3: {time1 == time3}")
print(f"time1 != time2: {time1 != time2}")
# Find min/max
times_list = [time1, time2, time3]
earliest = min(times_list)
latest = max(times_list)
print(f"\nEarliest: {earliest}")
print(f"Latest: {latest}")
# Check if in time range
check =
start = time(9, 0)
end = time(17, 0)
in_range = start <= check <= end
print(f"\n{check} in range [{start}, {end}]: {in_range}")
# Sort times
unsorted = [
time(15, 30),
time(9, 0),
time(12, 15)
]
print("\nBefore sort:")
for t in unsorted:
print(f" {t}")
sorted_times = sorted(unsorted)
print("After sort:")
for t in sorted_times:
print(f" {t}")
# Business hours check
business_start = time(9, 0)
business_end = time(17, 0)
print("\nBusiness hours check:")
test_times = [
time(8, 30),
time(12, 0),
time(18, 0)
]
for t in test_times:
is_during_business = business_start <= t < business_end
print(f"{t} during business: {is_during_business}")
# Midnight crossing
late = time(23, 0)
early = time(1, 0)
print(f"\n23:00 < 01:00: {late < early}") # True (earlier in day)
# Special time comparisons
print("\nSpecial comparisons:")
print(f"Midnight: {time.min}")
print(f"Almost midnight: {time.max}")
print(f"Noon: {time(12, 0)}")
noon = time(12, 0)
print(f"10:00 < noon: {time(10, 0) < noon}")
print(f"14:00 > noon: {time(14, 0) > noon}")
# Filter times
all_times = [
time(8, 0),
time(10, 0),
time(14, 0),
time(18, 0)
]
morning_times = [t for t in all_times if t < time(12, 0)]
afternoon_times = [t for t in all_times if t >= time(12, 0)]
print(f"\nMorning times: {morning_times}")
print(f"Afternoon times: {afternoon_times}")
# Compare times
from datetime import time
# Compare times
time1 = time(9, 30)
time2 = time(14, 45)
time3 = time(9, 30)
print(f"Time 1: {time1}")
print(f"Time 2: {time2}")
print(f"Time 3: {time3}")
print()
# Comparison operators
print(f"time1 < time2: {time1 < time2}")
print(f"time1 > time2: {time1 > time2}")
print(f"time1 <= time2: {time1 <= time2}")
print(f"time1 >= time2: {time1 >= time2}")
# Equality
print(f"\ntime1 == time2: {time1 == time2}")
print(f"time1 == time3: {time1 == time3}")
print(f"time1 != time2: {time1 != time2}")
# Find min/max
times_list = [time1, time2, time3]
earliest = min(times_list)
latest = max(times_list)
print(f"\nEarliest: {earliest}")
print(f"Latest: {latest}")
# Check if in time range
check =
start = time(9, 0)
end = time(17, 0)
in_range = start <= check <= end
print(f"\n{check} in range [{start}, {end}]: {in_range}")
# Sort times
unsorted = [
time(15, 30),
time(9, 0),
time(12, 15)
]
print("\nBefore sort:")
for t in unsorted:
print(f" {t}")
sorted_times = sorted(unsorted)
print("After sort:")
for t in sorted_times:
print(f" {t}")
# Business hours check
business_start = time(9, 0)
business_end = time(17, 0)
print("\nBusiness hours check:")
test_times = [
time(8, 30),
time(12, 0),
time(18, 0)
]
for t in test_times:
is_during_business = business_start <= t < business_end
print(f"{t} during business: {is_during_business}")
# Midnight crossing
late = time(23, 0)
early = time(1, 0)
print(f"\n23:00 < 01:00: {late < early}") # True (earlier in day)
# Special time comparisons
print("\nSpecial comparisons:")
print(f"Midnight: {time.min}")
print(f"Almost midnight: {time.max}")
print(f"Noon: {time(12, 0)}")
noon = time(12, 0)
print(f"10:00 < noon: {time(10, 0) < noon}")
print(f"14:00 > noon: {time(14, 0) > noon}")
# Filter times
all_times = [
time(8, 0),
time(10, 0),
time(14, 0),
time(18, 0)
]
morning_times = [t for t in all_times if t < time(12, 0)]
afternoon_times = [t for t in all_times if t >= time(12, 0)]
print(f"\nMorning times: {morning_times}")
print(f"Afternoon times: {afternoon_times}")
combine.py
# Combine date and time
from datetime import date, time, datetime
# Combine date and time
d = date(2025, 1, 29)
t = time(14, 30, 0)
# Combine using datetime
dt1 = datetime.combine(d, t)
print(f"Date + Time: {dt1}")
# Shorthand: create datetime directly
dt2 = datetime(2025, 1, 29, 14, 30, 0)
print(f"Direct datetime: {dt2}")
# Today at specific time
today_at_9 = datetime.combine(date.today(), time(9, 0))
print(f"\nToday at 9:00: {today_at_9}")
# Start and end of day
start_of_day = datetime.combine(d, time.min)
end_of_day = datetime.combine(d, time.max)
print(f"\nStart of day: {start_of_day}")
print(f"End of day: {end_of_day}")
# Extract date and time from datetime
now = datetime.now()
extracted_date = now.date()
extracted_time = now.time()
print(f"\nNow: {now}")
print(f"Extracted date: {extracted_date}")
print(f"Extracted time: {extracted_time}")
# Common datetime patterns
print("\nCommon datetimes:")
# Today at specific time
today = date.today()
today_at_noon = datetime.combine(today, time(12, 0))
print(f"Today at noon: {today_at_noon}")
# Tomorrow at specific time
from datetime import timedelta
tomorrow = today + timedelta(days=1)
tomorrow_at_9 = datetime.combine(tomorrow, time(9, 0))
print(f"Tomorrow at 9:00: {tomorrow_at_9}")
# Next Monday at 9 AM
days_until_monday = (7 - today.weekday()) % 7
if days_until_monday == 0:
days_until_monday = 7
next_monday = today + timedelta(days=days_until_monday)
next_monday_9am = datetime.combine(next_monday, time(9, 0))
print(f"Next Monday 9 AM: {next_monday_9am}")
# Schedule times
print("\nScheduled times for tomorrow:")
schedule_times = [
time(9, 0),
time(11, 30),
time(14, 0),
time(16, 30)
]
for t in schedule_times:
dt = datetime.combine(tomorrow, t)
print(f" {dt}")
# Replace time in datetime
dt = datetime.now()
new_time = dt.replace(hour=15, minute=30, second=0, microsecond=0)
print(f"\nOriginal: {dt}")
print(f"New time: {new_time}")
Common Operations
- Access hour, minute, second components
- Format to string
- Compare times
- Combine with date to make datetime
Immutability
Times are immutable - operations return new instances.
time_creation
Creating time objects with specific hour, minute, second, and microsecond values
current_time
Getting current time from datetime.now()
time_components
Accessing hour, minute, second, microsecond, and converting to 12-hour format
time_comparison
Comparing times and checking time ranges
datetime_combine
Combining date and time objects into datetime
Exercise: practical.py
Validate business hours, round times to intervals, and generate time slots