Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Pandas program to convert a string of date into time
In this program, we will convert date strings like "24 August 2020" into datetime format using Pandas. The to_datetime() function automatically parses various date string formats and converts them to standardized datetime objects.
Algorithm
Step 1: Define a Pandas series containing date strings. Step 2: Convert these date strings into datetime format using to_datetime(). Step 3: Print the results.
Example
Let's convert different date string formats to datetime ?
import pandas as pd
series = pd.Series(["24 August 2020", "25 December 2020 20:05"])
print("Original Series:")
print(series)
datetime_series = pd.to_datetime(series)
print("\nDateTime Format:")
print(datetime_series)
Original Series: 0 24 August 2020 1 25 December 2020 20:05 dtype: object DateTime Format: 0 2020-08-24 00:00:00 1 2020-12-25 20:05:00 dtype: datetime64[ns]
Working with Different Date Formats
The to_datetime() function can handle various date string formats automatically ?
import pandas as pd
# Different date string formats
date_strings = pd.Series([
"2020-08-24",
"24/08/2020",
"Aug 24, 2020",
"2020-08-24 14:30:00"
])
print("Original date strings:")
print(date_strings)
converted_dates = pd.to_datetime(date_strings)
print("\nConverted to datetime:")
print(converted_dates)
Original date strings: 0 2020-08-24 1 24/08/2020 2 Aug 24, 2020 3 2020-08-24 14:30:00 dtype: object Converted to datetime: 0 2020-08-24 00:00:00 1 2020-08-24 00:00:00 2 2020-08-24 00:00:00 3 2020-08-24 14:30:00 dtype: datetime64[ns]
Key Points
- The
to_datetime()function automatically infers date formats - When no time is specified, it defaults to 00:00:00
- The result is a datetime64[ns] dtype for efficient operations
- Use
formatparameter for specific date formats to improve performance
Conclusion
Pandas to_datetime() function provides a simple way to convert date strings into datetime objects. It automatically handles various date formats and creates standardized datetime64 objects suitable for time-based operations.
Advertisements
