I tried this code to convert string of dates into another format but i have number of strings which is not taken by this code.
import dateparser
dateparser.parse(str1[0], date_formats=['%d %B %Y'] )
Can anyone help me?
I tried this code to convert string of dates into another format but i have number of strings which is not taken by this code.
import dateparser
dateparser.parse(str1[0], date_formats=['%d %B %Y'] )
Can anyone help me?
You can convert your date format using datetime, which is available in the standard library:
from datetime import datetime
x = '30 Jan 2010'
res_single = datetime.strptime(x, '%d %b %Y').strftime('%Y-%m-%d')
# '2010-01-30'
lst = ['30 Jan 2015', '10 Dec 2010', '20 Apr 2020', '15 Feb 2005']
res_lst = [datetime.strptime(x, '%d %b %Y').strftime('%Y-%m-%d') for x in lst]
# ['2015-01-30', '2010-12-10', '2020-04-20', '2005-02-15']
You can use datetime and a straightforward for loop.
Preparations:
from datetime import datetime #import
dates = ['20 Feb 2010', '21 Mar 2012', '22 Apr 2014', '24 May 2016'] #sample dates
parsed_dates = [] #initialise empty list to store the parsed dates in
Actual loop:
for date in dates:
d_parsed = datetime.strptime(date, '%d %b %Y').strftime('%Y-%m-%d') #transform date
parsed_dates.append(d_parsed) #add transformed date to new list
This results in
print(parsed_dates)
#>>> ['2010-02-20', '2012-03-21', '2014-04-22', '2016-05-24']
If your dates are hidden but always in the same way - e.g. always preceded by a string of different lengths but situated in the end, as your example in the comments - use this code:
from datetime import datetime #import
hidden_dates = ['For example16 Apr 2018','another example04 Apr 2018', '20 Feb 2010', 'testdtas_21 Mar 2012', 'some characters24 22 Apr 2014', 'words 24 May 2016'] #sample dates
parsed_dates = [] #initialise empty list to store the parsed dates in
for hidden_d in hidden_dates:
date = hidden_d[-11:]
d_parsed = datetime.strptime(date, '%d %b %Y').strftime('%Y-%m-%d') #transform date
parsed_dates.append(d_parsed) #add transformed date to new list
print(parsed_dates)
#>>> ['2010-02-20', '2012-03-21', '2014-04-22', '2016-05-24']