Instruction
Let's review what we've learned.
Remember: To work with datetime objects, you must first import the datetime module!
-
To create objects from the
datetimemodule, use:time_object = datetime.time(9, 30, 0) date_object = date(2018, 12, 1) datetime_object = datetime.datetime(2018, 12, 1, 9, 45, 0)
-
To get a specific part of an object, use the dot operator:
print(time_object.hour) print(date_object.year)
-
Objects from the
datetimemodule are immutable, but you can create a new object from an existing one:new_time_object = time_object.replace(minute=45)
- The
weekday()andisoweekday()functions return an integer representing the day of the week for a given date or datetime.
Theweekday()function returns an integer from 0 (Monday) to 6 (Sunday).
Theisoweekofday()function is similar, but returns a value from 1 (Monday) to 7 (Sunday) instead. -
When you subtract two
dates ordatetimes, you get atimedelta. You can also create atimedeltaand add it to or subtract it from adateordatetimeobject:sample_timedelta = datetime.timedelta(days=1)
- You can compare objects from the
datetimemodule using>,>=,<,<=, and==. Remember thatdatetime_a > datetime_bisTruewhendatetime_ais a later (more recent) point in time thandatetime_b. - To format a datetime object, use
strftime().
Ready for a short quiz before moving on?
Exercise
Click to continue.



