Getting only the date from datetime in Python is a common task in data analysis and processing. Python provides built-in libraries to handle date and time-related operations efficiently. In this tutorial, we will learn how to get only the date from datetime in Python.
Steps:
1. Import datetime module
We need to import the datetime module to use its functions and objects. To import the datetime module, use the following code:
1 |
import datetime |
2. Create a datetime object
We will create a datetime object to get the date from it. To create a datetime object, we can use the datetime() constructor with the year, month, day, hour, minute, and second values. Here is an example:
1 |
dt = datetime.datetime(2021, 3, 10, 15, 30, 45) |
Here, we have created a datetime object “dt” with year=2021, month=3, day=10, hour=15, minute=30, and second=45.
3. Get only the date from datetime
Now, to get only the date from datetime, we will use the date() method of the datetime object. Here is the code:
1 |
date_only = dt.date() |
Here, we have used the date() method on the datetime object “dt” and assigned the result to a new variable “date_only”.
4. Print the date only
Finally, we will print the date_only variable to verify if we have got only the date from datetime or not. Here is the code:
1 |
print(date_only) |
Here is the output:
2021-03-10
Full code:
1 2 3 4 5 |
import datetime dt = datetime.datetime(2021, 3, 10, 15, 30, 45) date_only = dt.date() print(date_only) |
Conclusion:
In this tutorial, we have learned how to get only the date from datetime in Python. We have used the datetime module, created a datetime object, and then used the date() method to get only the date from datetime. By following these simple steps, you can easily get only the date from datetime in Python.