I have the following pandas
dataframe
JavaScript
x
10
10
1
import pandas as pd
2
import datetime
3
4
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)]']})
5
foo
6
7
id time
8
0 1 [datetime.datetime(2021, 10, 20, 14, 29, 51), datetime.datetime(2021, 10, 20, 14, 46, 8)]
9
1 2 [datetime.datetime(2021, 10, 20, 15, 0, 44), datetime.datetime(2021, 10, 20, 16, 13, 42)]
10
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:
JavaScript
1
3
1
t = datetime.datetime(2021, 10, 20, 14, 29, 51)
2
t.strftime('%Y/%m/%d %H:%M:%S')
3
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 ?
Advertisement
Answer
You just need to use list comprehension inside apply
after converting string lists to actual lists with eval
:
JavaScript
1
2
1
foo.time.apply(lambda str_list: [item.strftime('%Y/%m/%d %H:%M:%S') for item in eval(str_list)])
2