Working with Dates and Time
The datetime module is the standard way to work with dates, times, and time intervals in Python.
python import datetime
1. datetime.date (Date only)
python today = datetime.date.today() print(f"Today's date: {today}") # YYYY-MM-DD print(f"Year: {today.year}")
2. datetime.time (Time only)
3. datetime.datetime (Date and Time)
This is the most common class.
python now = datetime.datetime.now() print(f"Current Date/Time: {now}")
Creating a specific datetime object
birthday = datetime.datetime(2000, 1, 1, 12, 0, 0) print(f"Birthday: {birthday}")
4. datetime.timedelta (Time Intervals)
Represents a duration or the difference between two datetime objects.
python from datetime import timedelta
one_week = timedelta(weeks=1) next_week = now + one_week print(f"Date next week: {next_week.date()}")
time_elapsed = now - birthday print(f"Time since birth (days): {time_elapsed.days}")