How to use the datetime module in Python

The datetime module in Python is a powerful tool for working with dates and times. It provides a wide range of functions for manipulating date and time values.

To use the datetime module, first import it into your program:

import datetime

Once imported, you can use the datetime module to create and manipulate date and time values. For example, you can create a datetime object that represents the current date and time:

now = datetime.datetime.now()

You can also use the datetime module to perform calculations with dates and times. For example, you can calculate the difference between two dates:

delta = now – datetime.datetime(2021, 1, 1)

The datetime module also provides a range of formatting options for displaying date and time values. For example, you can format a datetime object as a string:

formatted_date = now.strftime(“%Y-%m-%d %H:%M:%S”)

Finally, you can use the datetime module to convert between different time zones. For example, you can convert a datetime object from UTC to local time:

local_time = datetime.datetime.utcnow().astimezone()

These are just a few of the many features of the datetime module. For more information, refer to the official Python documentation.