![]() |
VOOZH | about |
In this article, we are going to see how to convert DateTime to date in Python. For this, we will use the strptime() method and Pandas module. This method is used to create a DateTime object from a string. Then we will extract the date from the DateTime object using the date() function and dt.date from Pandas in Python.
Classes for working with date and time are provided by the Python Datetime module. Numerous capabilities to deal with dates, times, and time intervals are provided by these classes. Python treats date and DateTime as objects, so when you work with them, you're really working with objects rather than strings or timestamps.
Syntax: datetime.strptime()
Parameters:
- arg: It can be integer, float, tuple, Series, Dataframe to convert into datetime as its datatype
- format: This will be str, but the default is None. The strftime to parse time, eg "%d/%m/%Y", note that "%f" will parse all the way up to nanoseconds.
In this example, We have created a datetime_str which is "24AUG2001101010", and its format is "%d%b%Y%H%M%S".
Output:
datetime string : 24AUG2001101010 2001-08-24 10:10:10 2001-08-24
In this example, We have created a datetime_str which is "100201095407", and its format is "%d%m%y%H%M%S".
Output:
datetime string : 100201095407 2001-02-10 09:54:07 2001-02-10
In this example, we take the present date and time and extracted its date from the object.
Output:
2021-08-07 06:30:20.227879 2021-08-07
Pandas provide a different set of tools using which we can perform all the necessary tasks on date-time data. Let’s try to understand with the examples discussed below.
The date value and the DateTime value are both displayed in the output using the print command. The DateTime values are first added to a column of a Pandas DataFrame. The DateTime value is then converted to a date value using the dt.date() function.
Output:
time 0 2022-7-16 11:05:00 1 2025-7-18 12:00:30 time 0 2022-07-16 1 2025-07-18