w3resource

Pandas Data Series: Convert a series of date strings to a timeseries

Pandas: Data Series Exercise-27 with Solution

Write a Pandas program to convert a series of date strings to a timeseries.

Sample Solution :

Python Code :

import pandas as pd
date_series = pd.Series(['01 Jan 2015', '10-02-2016', '20180307', '2014/05/06', '2016-04-12', '2019-04-06T11:20'])
print("Original Series:")
print(date_series)
print("\nSeries of date strings to a timeseries:")
print(pd.to_datetime(date_series))

Sample Output:

Original Series:
0         01 Jan 2015
1          10-02-2016
2            20180307
3          2014/05/06
4          2016-04-12
5    2019-04-06T11:20
dtype: object

Series of date strings to a timeseries:
0   2015-01-01 00:00:00
1   2016-10-02 00:00:00
2   2018-03-07 00:00:00
3   2014-05-06 00:00:00
4   2016-04-12 00:00:00
5   2019-04-06 11:20:00
dtype: datetime64[ns]

Explanation:

date_series = pd.Series(['01 Jan 2015', '10-02-2016', '20180307', '2014/05/06', '2016-04-12', '2019-04-06T11:20']): This code creates a Pandas Series object 'date_series' containing six strings representing dates in different formats.

pd.to_datetime(date_series): The code then applies the pd.to_datetime() method to the Pandas Series object 'date_series'. This method attempts to convert the input strings into Pandas Timestamp objects, which represent specific points in time.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Pandas program to compute difference of differences between consecutive numbers of a given series.
Next: Write a Pandas program to get the day of month, day of year, week number and day of week from a given series of date strings.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.