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!

Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
123
  • 39
  • 3

4 Answers4

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']
MPA
  • 1,011
  • 7
  • 22
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']
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']
Pygirl
  • 12,969
  • 5
  • 30
  • 43
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']
Baragorn
  • 126
  • 1
  • 3
  • 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'? – 123 Dec 19 '20 at 15:48
  • 1
    for elem in date_time_list: if elem is None: date_list.append(None) continue date,time = elem.split() date_list.append(date) – Baragorn Dec 20 '20 at 06:34