How To Get Only Date From Datetime In Python

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:

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:

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:

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:

Here is the output:

2021-03-10

Full code:

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.