Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

String ('yearQ1-4') to datetime

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading