Reputation: 955
I have the following list:
list1 = [{'time_period': '202004130000', 'count': 16859},
{'time_period': '202004140000', 'count': 21557}]
The value for time_period
is a string but I need to change it to a date. How can do this?
I tried the following but it is not correct:
for x in list1:
x['time_period'] = x['time_period'].strftime('%Y-%m-%d')
Upvotes: 0
Views: 31
Reputation: 1475
Your string appears to have format %Y%m%d%H%M
.
So if you want a datetime object (date), you would use
from datetime import datetime
x['time_period']=datetime.strptime(x['time_period'],'%Y%m%d%H%M')
Otherwise, if you're saying you want it formatted differently, you would use
x['time_period']=datetime.strptime(x['time_period'],'%Y%m%d%H%M').strftime('%Y-%m-%d')
which would replace the input format with the one you specified.
This is a good reference: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
Upvotes: 1