Home > Back-end >  transform a list of datetimes in a pandas column to list of strings
transform a list of datetimes in a pandas column to list of strings

Time:09-23

I have the following pandas dataframe

import pandas as pd
import datetime

foo = pd.DataFrame({'id': [1,2], 'time' :['[datetime.datetime(2021, 10, 20, 14, 29, 51), datetime.datetime(2021, 10, 20, 14, 46, 8)]', '[datetime.datetime(2021, 10, 20, 15, 0, 44), datetime.datetime(2021, 10, 20, 16, 13, 42)]']})
foo

   id   time
0   1   [datetime.datetime(2021, 10, 20, 14, 29, 51), datetime.datetime(2021, 10, 20, 14, 46, 8)]
1   2   [datetime.datetime(2021, 10, 20, 15, 0, 44), datetime.datetime(2021, 10, 20, 16, 13, 42)]

I would like to transform each element of the lists in the time column to a string with the format '%Y/%m/%d %H:%M:%S'

I know I can do this:

t = datetime.datetime(2021, 10, 20, 14, 29, 51)
t.strftime('%Y/%m/%d %H:%M:%S')

to yield the value '2021/10/20 14:29:51',

but I do not know how to do this operation for every string element of each list in the time column.

Any help ?

CodePudding user response:

You just need to use list comprehension inside apply after converting string lists to actual lists with eval:

foo.time.apply(lambda str_list: [item.strftime('%Y/%m/%d %H:%M:%S') for item in eval(str_list)])

CodePudding user response:

You can separate the list into rows first with explode and then use the dt accessor in pandas:

(foo
 .explode('time')
 .assign(time=lambda x: x.time.dt.strftime('%Y/%m/%d %H:%M:%S'))
)
  • Related