Reputation: 39
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!
Upvotes: 3
Views: 1718
Reputation: 146
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']
Upvotes: 1
Reputation: 481
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']
Upvotes: 1
Reputation: 13349
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']
Upvotes: 1
Reputation: 1117
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']
Upvotes: 2