Understanding Python Datetime
Before adding time, it is important to understand the fundamental components of the datetime module.
Core Datetime Components
The datetime module provides several key classes:
| Class |
Description |
date |
Represents a date (year, month, day) |
time |
Represents a time (hour, minute, second) |
datetime |
Combines date and time |
timedelta |
Represents a duration of time |
Creating Datetime Objects
You can create datetime objects in several ways. Let's create a simple Python script to see how.
Open the integrated terminal in the WebIDE and navigate to the project directory if you are not already there.
cd ~/project
Create a new file named datetime_basics.py in the ~/project directory using the WebIDE file explorer or the command line.
touch datetime_basics.py
Open datetime_basics.py in the WebIDE editor and add the following code:
from datetime import date, time, datetime
## Creating a date object
current_date = date.today()
print(f"Current date: {current_date}")
## Creating a time object (from current datetime)
current_time = datetime.now().time()
print(f"Current time: {current_time}")
## Creating a datetime object
current_datetime = datetime.now()
print(f"Current datetime: {current_datetime}")
## Creating a specific datetime object
specific_datetime = datetime(2023, 6, 15, 14, 30, 45)
print(f"Specific datetime: {specific_datetime}")
Save the file. Now, run the script from the terminal:
python datetime_basics.py
You will see output similar to this:
Current date: YYYY-MM-DD
Current time: HH:MM:SS.microseconds
Current datetime: YYYY-MM-DD HH:MM:SS.microseconds
Specific datetime: 2023-06-15 14:30:45
This shows how to create basic date, time, and datetime objects.
Key Datetime Attributes
datetime objects have attributes like year, month, day, hour, minute, and second that you can access.
Let's add to our datetime_basics.py script to demonstrate accessing these attributes.
Open datetime_basics.py again and add the following lines at the end:
print(f"Year: {specific_datetime.year}")
print(f"Month: {specific_datetime.month}")
print(f"Day: {specific_datetime.day}")
print(f"Hour: {specific_datetime.hour}")
print(f"Minute: {specific_datetime.minute}")
print(f"Second: {specific_datetime.second}")
Save the file and run it again:
python datetime_basics.py
The output will now include the individual components of the specific_datetime:
Current date: YYYY-MM-DD
Current time: HH:MM:SS.microseconds
Current datetime: YYYY-MM-DD HH:MM:SS.microseconds
Specific datetime: 2023-06-15 14:30:45
Year: 2023
Month: 6
Day: 15
Hour: 14
Minute: 30
Second: 45
Understanding these fundamentals is the first step to performing time additions.