The datetime Module
Python provides the datetime
module for working with dates and times. It includes classes for manipulating dates, times, and date-time combinations.
Working with Dates
The date
class represents a date (year, month, day).
from datetime import date
today = date.today()
print(today) # Output: e.g., 2023-06-01
birthday = date(1990, 5, 15)
print(birthday) # Output: 1990-05-15
days_till_birthday = (birthday - today).days
print(days_till_birthday) # Output: e.g., -4748
Working with Times
The time
class represents a time (hour, minute, second, microsecond).
from datetime import time
current_time = time(18, 30, 0) # 6:30 PM
print(current_time) # Output: 18:30:00
meeting_time = time(14, 0, 0) # 2:00 PM
print(meeting_time) # Output: 14:00:00
Time Formatting and Parsing
You can format and parse date and time objects using the strftime()
and strptime()
methods.
from datetime import datetime
now = datetime.now()
print(now) # Output: e.g., 2023-06-01 18:45:30.123456
formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_time) # Output: e.g., 2023-06-01 18:45:30
parsed_time = datetime.strptime("2023-06-01 18:45:30", "%Y-%m-%d %H:%M:%S")
print(parsed_time) # Output: 2023-06-01 18:45:30
In the next chapter, we'll explore Python libraries and frameworks, which provide a vast collection of pre-built tools and functionalities for various domains.