Creating a Timeseries from a Series of Date-Strings

This thread will cover different methods of an important technique used in data science and analysis projects i.e., converting a series of dates that are of type string or object into a series of dates where each date is of type date or datetime. There are several methods of achieving this and few are discussed below with example code for each method:

1. Using "pd.to_datetime()" method:

  • Pandas has a method pd.to_datetime() which can be used to convert a given argument to a Pandas DateTime object.
  • This method returns a Pandas DatetimeIndex object or a Series object of datetime64[ns] dtype, depending on the input argument.

2. Using "strptime()" method:

  • The Datetime library has a method strptime() which allows you to convert a date string with a specified format to a datetime64[ns] object.
  • To use this method, we first define a lambda function using strptime() and then we apply this lambda function to all elements in the series using apply() method.

3. Using "parse" method:

  • The parse() method in the dateutil.parser library allows you to convert a date string in a variety of formats to a datetime64[ns] object.
  • This method is applied to each element in the series using apply() method of series.

4. Using NumPy library:

  • NumPy allows creating an array of datetime64 elements by specifying the datatype in the np.array() constructor.
  • We can use this method to first convert our date-strings series into a NumPy array of type datetime64[ns].
  • Then, we can convert this NumPy array back into a series object using pd.Series() constructor.