How to Use the Datetime Python Module

The Datetime Python module, integrated right into Python’s standard library, makes it simple to work with dates and times.

You can easily perform operations such as extracting the date from a string, manipulating dates and times, formatting dates and times, performing arithmetic on dates, and much more. This tutorial will focus on how to use this powerful tool effectively.

Step 1: Importing the datetime module

We first need to import the datetime module before we can use it. Like any other module, all you have to do is type ‘import datetime’. Here’s how:

Step 2: Working with Date and Time

With the datetime module, you can create new date objects, which allows us to format, calculate or analyze easily. Here’s an example of creating a date object:

The values 2021, 5, 20 represent the year, month, and day respectively. To print the date represented by this object:

2021-05-20

Step 3: Printing today’s date

The datetime module also has built-in functions that help us easily retrieve the current date. Here’s an example:

2022-04-19

Step 4: Formatting the Date

Dates can be formatted in Python using the strftime function, which stands for string format time. This function not only works on datetime objects but also on time and date objects. Below is a simple example:

April 19, 2022

In the code above, the strftime method converts a datetime object into a string format where %B represents the full month name, %d represents the numeric day of the month, and %Y represents the 4-digit year.

The full code:

2021-05-20
2023-07-19
July 19, 2023

Conclusion

The Python datetime module is a powerful tool with many useful functions, making date and time manipulation in Python a breeze.

While this tutorial covers the basics, there’s a whole lot more you can do with dates, times, and timedeltas. Keep exploring the official Python datetime documentation to learn more about other functionalities not covered here. Happy Coding!