String ('yearQ1-4') to datetime

Question:

What is a most efficient way to go from list_of_strings to expected_result_in_datetime?

list_of_strings = ['2021Q1', '2021Q2', '2021Q3', '2021Q4']

expected_result_in_datetime = ['2020-12-31', '2021-03-31', '2021-06-31', '2021-09-30'] 

Asked By: Henrik

||

Answers:

Convert values to quarters, subtract one quarter and convert to datetimes:

d = (pd.PeriodIndex(list_of_strings, freq='Q') - 1).to_timestamp(how='end').floor('D')
print(d)
DatetimeIndex(['2020-12-31', '2021-03-31', '2021-06-30', '2021-09-30'], 
              dtype='datetime64[ns]', freq=None)

Or convert values to datetimes with subtract 1 day:

d = pd.to_datetime(list_of_strings) - pd.Timedelta('1 day')
print(d)
DatetimeIndex(['2020-12-31', '2021-03-31', '2021-06-30', '2021-09-30'], 
              dtype='datetime64[ns]', freq=None)
Answered By: jezrael
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.