0

String in the input list is formatted as 'yyyy-mm-dd hh:mm:ss'. The function should return a list of strings where each element in the returned list contains only the date in the 'yyyy-mm-dd' format e.g

lst = ['2019-11-29 12:50:54', '2019-11-28 12:46:53', '2019-11-27 12:46:10']

expected result ['2019-11-29', 2019-11-28, 2019-11-27']

3
  • 4
    Can you not just slice the first 10 chars? eg result = [el[:10] for e in lst] ? Commented Mar 12, 2020 at 20:47
  • [k.split()[0] for k in lst] would work as well, but not that good Commented Mar 12, 2020 at 20:59
  • What is the issue, exactly? Have you tried anything, done any research? Stack Overflow is not a free code writing service. See: How to Ask, help center, meta.stackoverflow.com/questions/261592/…. Commented Mar 12, 2020 at 21:23

2 Answers 2

3

Using datetime and specifying desired date formats, you can do something like

new_list = [datetime.strptime(item, "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d") for item in lst ]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks , this work too, though I wanted to avoid using datetime at first
0

Looping through the list you can slice the first n characters in the string using the following - change 11 to the desired length depending on your needs

for i in range(len(lst)):
    lst[i] = lst[i][:11]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.