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:
1 |
import datetime |
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:
1 |
new_date = datetime.date(2021, 5, 20) |
The values 2021, 5, 20 represent the year, month, and day respectively. To print the date represented by this object:
1 |
print(new_date) |
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:
1 2 |
today = datetime.date.today() print(today) |
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:
1 2 3 |
date = datetime.date.today() formatted_date = date.strftime("%B %d, %Y") print(formatted_date) |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import datetime # Create a date object new_date = datetime.date(2021, 5, 20) print(new_date) # Print today's date today = datetime.date.today() print(today) # Format the Date date = datetime.date.today() formatted_date = date.strftime("%B %d, %Y") print(formatted_date) |
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!