w3resource

Python Pandas: Convert a series of date strings to a timeseries

Python 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]

Python 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 Python skills with w3resource's quiz



Python: Tips of the Day

Python: Membership Testing in a Collection

>>> a = ('one', 'two', 'three', 'four', 'five')
>>> if 'one' in a:
...     print('The tuple contains one.')
... 
The tuple contains one.
>>> b = {0: 'zero', 1: 'one', 2: 'two', 3: 'three'}
>>> if 2 in b.keys():
...     print('The dict has the key of 2.')
... 
The dict has the key of 2.