Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Time
Date
Datetime
Summary
14. Summary

Instruction

Let's review what we've learned.

Remember: To work with datetime objects, you must first import the datetime module!

  1. To create objects from the datetime module, use:

    time_object = datetime.time(9, 30, 0)
    date_object = date(2018, 12, 1)
    datetime_object = datetime.datetime(2018, 12, 1, 9, 45, 0)
    
  2. To get a specific part of an object, use the dot operator:

    print(time_object.hour)
    print(date_object.year)
    
  3. Objects from the datetime module are immutable, but you can create a new object from an existing one:

    new_time_object = time_object.replace(minute=45)
  4. The weekday() and isoweekday() functions return an integer representing the day of the week for a given date or datetime.
    The weekday() function returns an integer from 0 (Monday) to 6 (Sunday).
    The isoweekofday() function is similar, but returns a value from 1 (Monday) to 7 (Sunday) instead.
  5. When you subtract two dates or datetimes, you get a timedelta. You can also create a timedelta and add it to or subtract it from a date or datetime object:

    sample_timedelta = datetime.timedelta(days=1)
  6. You can compare objects from the datetime module using >, >=, <, <=, and ==. Remember that datetime_a > datetime_b is True when datetime_a is a later (more recent) point in time than datetime_b.
  7. To format a datetime object, use strftime().

Ready for a short quiz before moving on?

Exercise

Click Next exercise to continue.