To define specific date and time data within a Python program, you use the constructor of the datetime class.
From the created datetime object, you can easily extract individual information such as year, month, day, hour, minute, and second as attributes. This article explains the basic method for generating an object with a specific date and time and accessing its components.
Basics of the datetime Constructor
When generating a datetime object, at least three arguments are required: Year, Month, and Day. Time arguments (hour, minute, second, microsecond) are optional; if omitted, they default to 0.
# Syntax
datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0)
Implementation Example: Defining Event Start Time and Getting Elements
In this example, we define the start date and time for a fictional “System Maintenance” event and display its details individually.
Source Code
from datetime import datetime
# Generate a datetime object by specifying a specific date and time
# Argument order: Year, Month, Day, Hour, Minute, Second
# Here, we specify December 31, 2025, 23:59:30
maintenance_start = datetime(2025, 12, 31, 23, 59, 30)
# Check the generated object
print(f"Set Date/Time: {maintenance_start}")
print("-" * 20)
# Accessing each attribute (property)
# Parentheses () are not needed; access via variable_name.attribute_name
print(f"Year : {maintenance_start.year}")
print(f"Month : {maintenance_start.month}")
print(f"Day : {maintenance_start.day}")
print(f"Hour : {maintenance_start.hour}")
print(f"Minute : {maintenance_start.minute}")
print(f"Second : {maintenance_start.second}")
Execution Result
Set Date/Time: 2025-12-31 23:59:30
--------------------
Year : 2025
Month : 12
Day : 31
Hour : 23
Minute : 59
Second : 30
Explanation
- Object Creation: An object holding date and time information is created by passing numbers, such as
datetime(2025, 12, 31, ...). Note that specifying an invalid date (e.g., Month 13 or Day 32) will raise aValueError, so be careful with the validity of input values. - Accessing Attributes: You can access elements using dot notation, such as
d.yearord.hour. Since these are attributes and not methods, do not use()when calling them. These are frequently used in conditional logic (e.g.,if d.hour < 12:to determine if it is morning).
