Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pandas
python
communitycreator

How to convert a series of date-strings to a timeseries in pandas

Arslan Bajwa

In Python, the pandas library includes built-in functionalities that allow you to perform different tasks with only a few lines of code. One of these functionalities is the conversion of a pandas series of date-strings to a timeseries.

Method 1: Use map

In this method, we first initialize a pandas series. Then, we use the dateutil library to parse the input string format to represent a datetime format. Then, we map this converted format to the input pandas series.

#importing pandas and dateutil libraries
import pandas as pd
from dateutil.parser import parse as pr

#initializing date-string pandas series
series = pd.Series(['12 July 2021', '04-01-2001', '20020101', '2000/09/09', '2020-05-18', '2021-08-08T14:35'])

#parsing and mapping the date-strings to timeseries
result = series.map(lambda iterator: pr(iterator))
print(result)

Method 2: Use to_datetime

In this method, we first initialize a pandas series. Then we use the to_datetime() function of pandas to convert the given date-strings into the respective timeseries.

#importing pandas library
import pandas as pd

#initializing date-string pandas series
series = pd.Series(['12 July 2021', '04-01-2001', '20020101', '2000/09/09', '2020-05-18', '2021-08-08T14:35'])

#converting date-strings to timeseries
result = pd.to_datetime(series)
print(result)

RELATED TAGS

pandas
python
communitycreator
RELATED COURSES

View all Courses

Keep Exploring