Python Logo

Date


What is Python Date?

The Date class in Python represents a date in the Gregorian calendar. It is a subclass of the datetime class.

The Date class has three attributes:

  • year: The year of the date.
  • month: The month of the date.
  • day: The day of the date.

Creating Date objects

To create a Date object, you use the Date() constructor. The constructor takes three arguments: the year, the month, and the day. For example:

 

Python

from datetime import Date

my_date = Date(2023, 11, 6)
 

This code creates a Date object for the date November 6, 2023.

Accessing Date attributes

You can access the year, month, and day attributes of a Date object using the dot notation. For example:

 

Python

print(my_date.year)  # Outputs 2023
print(my_date.month)  # Outputs 11
print(my_date.day)  # Outputs 6
 

Formatting Date objects

You can format Date objects using the strftime() method. The strftime() method takes a format string as an argument and returns a string representation of the date in that format.

Here are some common format strings:

  • %Y: The year.
  • %m: The month.
  • %d: The day.

For example, the following code formats the my_date object in the format "MM/DD/YYYY":

 

Python

formatted_date = my_date.strftime("%m/%d/%Y")

print(formatted_date)  # Outputs 11/06/2023
 

Comparing Date objects

You can compare Date objects using the ==, !=, <, <=, >, and >= operators. For example:

 

Python

print(my_date == Date(2023, 11, 6))  # Outputs True
print(my_date != Date(2023, 11, 5))  # Outputs True
print(my_date < Date(2023, 11, 7))  # Outputs True
 

Conclusion

The Date class in Python is a powerful tool for representing and working with dates. By understanding how to use the Date class, you can write more efficient and accurate code.