3

I have a long list of dates in the form ["2019-11-01 00:15:00+01", "2019-11-01 00:30:00+01", "2019-11-01 00:45:00+01" ... and so on] in the type of strings. I would like to go through the list and remove the "00:15:00+01"-part. I have tried with a dummy list first, but I cant seem to make it work. How can I remove part of the string elements in a list?

    url = ['abcdc.com', 'tzr.com']
    for i in range(0,len(url)):
       if url[i].endswith('.com'):
          url[i] = url[:-4]

The code above only returns: url = [[],[]]. Why? Any help you be greatly appreciated!

1
  • 1
    url[i] = url[:-4] should be url[i] = url[i][:-4] Commented Dec 17, 2020 at 14:42

4 Answers 4

2

you could use split as:

dates = ["2019-11-01 00:15:00+01", "2019-11-01 00:30:00+01", "2019-11-01 00:45:00+01"]
new_dates = []
for date in dates:
    new_dates.append(date.split()[0])

print(new_dates)

['2019-11-01', '2019-11-01', '2019-11-01']
Sign up to request clarification or add additional context in comments.

Comments

1

You can use regex to extract only dates.

import re
x = [re.search(r'\d{4}-\d{2}-\d{2}', l).group(0) for l in li ] 

x:

['2019-11-01', '2019-11-01', '2019-11-01']

Comments

1

If I understood it correctly, would this do?

>>> url = ['abcdc.com', 'tzr.com']
>>> url = [x[:-4] if x.endswith('.com') else x for x in url]
>>> url
['abcdc', 'tzr']

Comments

1

this can solve your problem:

url = ['abcdc.com', 'tzr.com']
for i in range(0, len(url)):
    if url[i].endswith('.com'):
        url[i] = url[i][:-4]

A better way to solve your problem is by using split() to separate each element in data _time list, as so:

date_time_list =["2019-11-01 00:15:00+01", "2019-11-01 00:30:00+01", "2019-11-01 00:45:00+01"]
date_list = []

for elem in date_time_list:
     if elem is None:
         date_list.append(None)
         continue
     date,time = elem.split()
     date_list.append(date)
print(date_list)
>>> ['2019-11-01', '2019-11-01', '2019-11-01']

2 Comments

Thanks, that helps a lot! However, I realized I have a 'nan' in my list - and get this error message: "not enough values to unpack (expected 2, got 1)". Do you know how I could solve this without deleting the 'nan'?
for elem in date_time_list: if elem is None: date_list.append(None) continue date,time = elem.split() date_list.append(date)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.