I am currently studying Python String formatting. I have stucked on a problem
I have a string
s = "25Aug20"
I want to get the date month and year separately
sp_list = ['25', 'Aug', '20']
You can use slicing:
sp_list = [s[:2], s[2:5], s[5:]]
If you want to get an actual datetime object, use .strptime():
from datetime import datetime
s = "25Aug20"
print(datetime.strptime(s, "%d%b%y"))
this will print
2020-08-25 00:00:00
"25-08-2020") use mydatetime.strftime("%d-%m-%Y").You can use slicing, as already mentioned in another answer, but I will add that if there is any possibility that you might also need to process strings that use only a single character when dealing with single-digit dates, e.g. '5Aug20' (instead of '05Aug20' or ' 5Aug20'), then I suggest slicing relative to the end of the string to allow tolerance for this:
sp_list = [s[:-5], s[-5:-2], s[-2:]]
This should always work, provided only that the number of characters used for the year is always 2, and the number of characters used for the month is always 3.