Date and Time Objects in Python
Date and Time Objects
96
Python has a built-in module called "datetime" that provides various classes for working with dates and time. The module contains three main classes- datetime, date, and time.
- datetime class:
This class combines both date and time information. A datetime instance has attributes year, month, day, hour, minute, second, microsecond, and tzinfo (timezone information).
- date class:
This class deals with dates only. A date instance has attributes year, month, and day.
- time class:
This class handles time information only. A time instance has attributes hour, minute, second, microsecond, and tzinfo.
The datetime class is the most commonly used class in this module. We can create a datetime object using the constructor of the datetime class.
Here's an example:
from datetime import datetime now = datetime.now() # current date and time print("Current date and time:", now)
The output of the above code will be something like this:
Current date and time: 2022-06-30 19:58:43.017478
We can also create a datetime object by specifying the date and time components manually like this:
from datetime import datetime dt = datetime(year=2022, month=6, day=30, hour=10, minute=30, second=15) print(dt)
The output will be:
2022-06-30 10:30:15
We can perform various operations with the datetime objects, such as comparing two datetime objects, adding or subtracting time intervals, converting datetime objects to different string formats.
In summary, the datetime module provides classes and functions to work with dates, times, and time intervals in Python. It is a powerful tool that can simplify date and time calculations and formatting in Python programs.
March 25, 2023