Working with Date Objects
Now that we've covered the basics of the datetime
module, let's dive deeper into working with date objects.
Creating Date Objects
You can create date objects using the date
class from the datetime
module. Here's an example:
from datetime import date
## Create a date object
today = date(2023, 4, 18)
print(today) ## Output: 2023-04-18
You can also use the today()
method to get the current date:
from datetime import date
today = date.today()
print(today) ## Output: 2023-04-18
Accessing Date Components
Once you have a date object, you can access its individual components, such as the year, month, and day, using the following attributes:
from datetime import date
today = date(2023, 4, 18)
print(today.year) ## Output: 2023
print(today.month) ## Output: 4
print(today.day) ## Output: 18
Comparing Date Objects
You can compare date objects using the standard comparison operators, such as <
, >
, ==
, <=
, and >=
. This allows you to perform various date-related operations, such as checking if a date is before or after another date.
from datetime import date
today = date(2023, 4, 18)
tomorrow = date(2023, 4, 19)
print(today < tomorrow) ## Output: True
print(today > tomorrow) ## Output: False
print(today == tomorrow) ## Output: False
By mastering the basics of working with date objects, you'll be well on your way to more advanced date manipulation and formatting techniques.