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.
1 2 |
import datetime from datetime import date |
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.
1 2 |
print(date.today()) print(datetime.datetime.now()) |
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.
1 2 3 4 |
d = date(2019,10,21) t = datetime.time(15, 41, 22) print(d) print(t) |
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.
1 2 |
print(date.today() + datetime.timedelta(days=1)) print(datetime.datetime.now() + datetime.timedelta(hours=1)) |
The output will be:
2019-10-22 2019-10-21 16:41:22.673604
The full code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import datetime from datetime import date # Accessing current date and time print(date.today()) print(datetime.datetime.now()) # Creating specific date and time objects d = date(2019,10,21) t = datetime.time(15, 41, 22) print(d) print(t) # Adding to date and time print(date.today() + datetime.timedelta(days=1)) print(datetime.datetime.now() + datetime.timedelta(hours=1)) |
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.