Welcome to our comprehensive guide on leveraging the datetime module in Python, facilitated by none other than the acclaimed learn-by-doing platform, W3Schools. If you're eager to manipulate dates and times in your Python projects or automate date-based tasks, you're in the right place.

The Python datetime module offers a plethora of functionalities to handle dates and time, enabling you to extract, format, and perform calculations with dates. Let's dive into the world of datetime with W3Schools, your trusted companion on this coding journey.

Datetime Objects
At the core of datetime module lie datetime objects, which encapsulate date and time information. These objects are Instantiateable using the datetime() function, as shown:

from datetime import datetime
now_d = datetime.now()
Basic datetime Constructor

The simplest way of creating a datetime object is by using the .now() method, as indicated above. Here's what you'll get:
print(now_d)
# Output: 2022-07-14 12:00:00.000000
Custom datetime Constructor

If you wish to work with a specific date and time, you can manually set it, like so:
custom_d = datetime(2022, 7, 14, 12, 30, 45)
print(custom_d)
# Output: 2022-07-14 12:30:45
Formatting Dates

Python's strftime() function is your friend when it comes to formatting dates and times per your requirements. W3Schools' interactive examples make learning strftime a breeze.
strftime() in Action




















Use strftime() to format the datetime object 'now_d' like you desire:
formatted_now = now_d.strftime('%Y-%m-%d %H:%M:%S')
print(formatted_now)
# Output: 2022-07-14 12:00:00
Pick Your Format
Explore different format directives in the strftime() function, such as %Y for year, %m for month, and %d for day. Mix and match them to return your desired date format.
Calculations with datetime
You can also perform arithmetic operations with date and time objects. Say you wish to find out what time it will be after a certain period.
Adding to datetime
Adding seconds, minutes, hours, or even days to a datetime object is straightforward:
from datetime import timedelta
two_hours_later = now_d + timedelta(hours = 2)
print(two_hours_later)
# Output: 2022-07-14 14:00:00
Subtracting from datetime
Similarly, find out past times just as effortlessly:
two_hours_ago = now_d - timedelta(hours = 2)
print(two_hours_ago)
# Output: 2022-07-14 10:00:00
With W3Schools' robust guidance on Python's datetime functions and interactive examples, you're ready to concoct formidable date and time-based Python applications. Happy coding!