Python datetime Module

The datetime module is a built-in Python module that provides classes for working with dates and times. It includes classes such as date, time, datetime, timedelta, etc.

Here's an example of how to use the datetime module in Python:

import datetime

# Get the current date and time
now = datetime.datetime.now()

# Print the current date and time
print("Current date and time:")
print(now)

# Print the date and time components separately
print("Date and time components:")
print(now.year)
print(now.month)
print(now.day)
print(now.hour)
print(now.minute)
print(now.second)
So‮‬urce:www.theitroad.com

Output:

Current date and time:
2022-03-01 15:45:23.425236
Date and time components:
2022
3
1
15
45
23

In the example above, we imported the datetime module and used the now() function to get the current date and time. We then printed the current date and time using the print() function. Finally, we printed the date and time components separately using the attributes of the datetime object.

We can also create a datetime object by passing arguments to the datetime() constructor, like this:

import datetime

# Create a datetime object
dt = datetime.datetime(2022, 3, 1, 15, 45, 23)

# Print the datetime object
print(dt)

Output:

2022-03-01 15:45:23

In this example, we created a datetime object representing March 1st, 2022 at 3:45:23 PM, and printed it using the print() function.