Logo

Developer learning path

Python

Date and Time Objects in Python

Date and Time Objects

96

#description

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.

  1. 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).

  1. date class:

This class deals with dates only. A date instance has attributes year, month, and day.

  1. 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

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.