Creating date objects

You can instantiate date objects from the date class. A date object represents a date (year, month and day). You can also instantiate a datetime object from the datetime class. A datetime object represents a date + time (year, month, day, hours, minutes, seconds).

import datetime

d = datetime.date(2014, 9, 7)
dt = datetime.datetime(2020, 12, 24, 22, 9, 24)
print(d)
print(dt)
Code Explanation

This Python code snippet illustrates the creation and printing of date and datetime objects using the datetime module, specifically focusing on setting specific dates and times:

  1. Importing the datetime module: This module provides the functionality necessary to create, manipulate, and retrieve date and time information. It’s essential for working with dates and times in Python, offering a range of classes and methods to handle different temporal aspects.
  2. Creating a date object: The code defines a date object d using datetime.date(2014, 9, 7). This constructs a date object representing September 7, 2014. The date class is used here to create a date by specifying the year, month, and day as arguments. This object will only contain date information without any time details.
  3. Creating a datetime object: Similarly, a datetime object dt is created using datetime.datetime(2020, 12, 24, 22, 9, 24). This method constructs a datetime object representing December 24, 2020, at 22:09:24 (10:09:24 PM). Unlike the date object, the datetime class captures both date and time information, making it suitable for more detailed timestamping needs.
  4. Printing the date and datetime objects:
    • Printing d outputs the date in a standard YYYY-MM-DD format, showing “2014-09-07”. This format is commonly used in databases and logging and is useful for readability and sorting.
    • Printing dt displays the datetime in a detailed YYYY-MM-DD HH:MM:SS format, showing “2020-12-24 22:09:24”. This includes both date and time down to the second, ideal for timestamping events to a precise moment.
Output
2014-09-07
2020-12-24 22:09:24