Home > database >  how to change the date format in every first element of a sublist
how to change the date format in every first element of a sublist

Time:11-28

I have a nested list like this: datelist = [["2019/04/12", 7.0], ["2019/02/09", 7.3], ["2018/08/14", 6.1]] I need to change the date format from yyyy/mm/dd/ to yyyy.mm.dd and then return the list as it is. So the result should be [["12.04.2019", 7.0], ["09.02.2019", 7.3], ["14.08.2018", 6.1]].

I'm a beginner, so I'm really not sure how to do it.

I tried the following:

import datetime
datelist = [datetime.datetime.strptime(str(i[0]), "%Y/%m/%d").strftime('%d.%m.%Y') for i in datelist]
print(datelist)

and the output was:

['12.04.2019', '09.02.2019', '14.08.2016']

So the change of the data format worked, but how do I return the the original nested list with the corrected data format?

I need to implement this as a function which takes lists like datelist as an input.

CodePudding user response:

It's simple:

datelist = [[datetime.datetime.strptime(str(i[0]), "%Y/%m/%d").strftime('%d.%m.%Y'), i[1]] for i in mylist]

When iterating throughout your list, you get back a list, knowing the position of your elements in the list helps, thus using i[0] for the first element (datetime), and i[1] for the second (number).

CodePudding user response:

You can update your script like below:

datelist = [[datetime.datetime.strptime(str(i[0]), "%Y/%m/%d").strftime('%d.%m.%Y'), i[1]] for i in datelist]
  • Related