0

I have a pandas column called time and it contains the year and semester. For instance in format ('YYYYSX') 2018S1. I want to convert the time format in YYYYSX into date

Input

   time
1  2019S2
2  2019S2
3  2020S1


output

   time
1  2019-09-30
2  2019-10-31
3  2020-01-31


free_123
  • 79
  • 1
  • 1
  • 3

1 Answers1

1
def convert(time):
    year = time[:4]
    semester = time[4:]
    conversions = {'S1': '-01-31' , 'S2': '-06-03', 'S3': '-09-30'}
    return pd.to_datetime(year + conversions[semester])

df['time'] = df.time.apply(convert)

returns :

    time
0   2019-06-03
1   2019-06-03
2   2020-01-31

I think there were some inconsistencies in your expected output, but you just need to put whatever semesters/dates you want in the conversions dictionary.

SimonR
  • 1,774
  • 1
  • 4
  • 10