How to Add Date and Time in Python

When programming in Python, there may be instances where you need to work with date and time objects. Accessing and manipulating this data could be useful in scenarios such as calculating the amount of time passed between two dates or scheduling automated jobs. In this tutorial, we will go over how to add date and time in Python.

Step 1: Importing the necessary libraries

The first thing we need to do is to import the Python libraries that we will be using. These are the datetime and date libraries.

Step 2: Accessing current date and time

To access the current date, we can use the today() method. For the current time, we use the datetime.now() method.

This will output the current date and time.

2019-10-21
2019-10-21 15:41:22.673604

Step 3: Creating date and time objects

Sometimes, we need to create specific date or time objects. Here is how we can do this in Python.

The output will be:

2019-10-21
15:41:22

Step 4: Adding to date and time

The last thing we’ll be going over is how to add to the date or time. We use the timedelta function from the datetime library to do this.

The output will be:

2019-10-22
2019-10-21 16:41:22.673604

The full code

Conclusion

In this tutorial, we’ve covered how to add date and time in Python. We learned how to access the current date and time, how to create specific date or time objects, and how to add to the date or time. This allows us to easily manipulate date and time objects in Python, which can be extremely beneficial in a variety of situations.