Python Datetime

Python, a versatile programming language, offers robust tools for date and time manipulation through its datetime module. This module is particularly useful for performing operations related to dates, times, and intervals. In this guide, we’ll explore key aspects of the Python datetime module, including working with dates, formatting date output, creating date objects, and using the strftime() method.

1. Python Dates

In Python, the datetime module provides classes for manipulating dates and times. To work with dates, you need to import the module:

from datetime import date

Once imported, you can access various functionalities. For instance, getting the current date is straightforward:

today =
print("Today's date:", today)

2. Date Output

When you print a date object, the default format is YYYY-MM-DD. This format is ISO 8601 compliant and is widely used in programming and data storage. For example:

print(today)  # Output: YYYY-MM-DD

3. Creating Date Objects

Creating a date object is simple. You can specify the year, month, and day to create a specific date:

my_date = date(2024, 1, 17)
print("The specified date is:", my_date)

This flexibility allows for the creation of any date, past or future, as long as it’s within the range of the datetime module.

4. The strftime() Method

The strftime() method is a powerful tool for formatting date objects into readable strings. It takes one argument, a format string, where you specify the format of the output date string. Here are some common directives:

  • %Y: Year with century as a decimal number.
  • %m: Month as a zero-padded decimal number.
  • %d: Day of the month as a zero-padded decimal number.
  • %A: Weekday as locale’s full name.


formatted_date = today.strftime("%B %d, %Y")
print("Formatted date:", formatted_date)

This example will output the date in the format “Month Day, Year” (e.g., “January 17, 2024”).

By mastering these aspects of the Python datetime module, you enhance your ability to handle dates and times in your applications. Whether you’re logging events, handling user input, or working with databases, these skills are indispensable in the world of programming. Keep experimenting with different methods and parameters to discover the full potential of Python’s datetime capabilities.