Python Datetime Type Hinting: A Comprehensive Guide
For datetime objects, type hinting makes your date and time operations more predictable and understandable.
This tutorial shows you how to use type hints with datetime and related objects.
Using datetime.datetime as a type hint
To specify that a parameter or return value is a datetime.datetime object, use the datetime type hint.
from datetime import datetime
def format_meeting_time(meeting_time: datetime) -> str:
return meeting_time.strftime("%Y-%m-%d %H:%M:%S")
meeting_time = datetime(2024, 11, 18, 15, 30)
formatted_time = format_meeting_time(meeting_time)
print(formatted_time)
Output:
2024-11-18 15:30:00
The function accepts a datetime object, formats it into a readable string, and returns the result.
The input meeting_time is converted into a standard YYYY-MM-DD HH:MM:SS format.
Using datetime.date as a type hint
You can use datetime.date to handle and hint at objects representing calendar dates.
from datetime import date
def days_until_event(event_date: date) -> int:
today = date.today()
delta = event_date - today
return delta.days
event_date = date(2024, 12, 25)
days_left = days_until_event(event_date)
print(days_left)
Output:
37
The function calculates the number of days between today and the given event date.
The subtraction between event_date and today yields a timedelta object, and its days attribute gives the remaining days.
Using datetime.time as a type hint
To work with time-of-day values without a date, use the datetime.time type hint.
from datetime import time
def is_within_office_hours(current_time: time) -> bool:
start = time(9, 0)
end = time(17, 0)
return start <= current_time <= end
current_time = time(14, 45)
office_open = is_within_office_hours(current_time)
print(office_open)
Output:
True
The function checks if the given time is between the office hours of 9:00 AM and 5:00 PM.
Using datetime.timedelta as type hint
Use datetime.timedelta to indicate durations or intervals.
from datetime import timedelta
def add_weeks(duration: timedelta, weeks: int) -> timedelta:
return duration + timedelta(weeks=weeks)
current_duration = timedelta(days=10)
new_duration = add_weeks(current_duration, 2)
print(new_duration)
Output:
24 days, 0:00:00
The function adds a specified number of weeks to the provided duration.
Here, the input duration of 10 days is extended by 14 days (2 weeks).
Using float or int for Unix timestamps
Unix timestamps, often represented as int or float, can also be type hinted.
from datetime import datetime
def timestamp_to_date(timestamp: float) -> str:
return datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")
timestamp = 1732271400.0
readable_date = timestamp_to_date(timestamp)
print(readable_date)
Output:
2024-11-22 12:30:00
The function converts a Unix timestamp into a human-readable datetime string.
The fromtimestamp method automatically interprets the timestamp based on the system timezone.
Type Hinting with Custom Date/Time Classes
When you create custom classes for handling dates or times, type hint them explicitly.
from datetime import date, timedelta
class EgyptianCalendar:
def __init__(self, current_date: date):
self.current_date = current_date
def add_days(self, days: int) -> date:
return self.current_date + timedelta(days=days)
calendar = EgyptianCalendar(date(2024, 11, 18))
new_date = calendar.add_days(5)
print(new_date)
Output:
2024-11-23
The custom class EgyptianCalendar stores a date and allows date manipulation.
The type hint for current_date ensures it accepts only date objects, and add_days returns a valid date.
Mokhtar is the founder of LikeGeeks.com. He is a seasoned technologist and accomplished author, with expertise in Linux system administration and Python development. Since 2010, Mokhtar has built an impressive career, transitioning from system administration to Python development in 2015. His work spans large corporations to freelance clients around the globe. Alongside his technical work, Mokhtar has authored some insightful books in his field. Known for his innovative solutions, meticulous attention to detail, and high-quality work, Mokhtar continually seeks new challenges within the dynamic field of technology.