2

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']
0

4 Answers 4

5

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
Sign up to request clarification or add additional context in comments.

2 Comments

Can you help me to convert it to 25-08-2020 ?
If you want to get a formatted string (i.e. "25-08-2020") use mydatetime.strftime("%d-%m-%Y").
2

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.

Comments

1

You can also use Regex

Ex:

import re

s="25Aug20"
print(re.match(r"(\d+)([A-Za-z]+)(\d+)", s).groups())
# -->('25', 'Aug', '20')

Comments

1

You can achieve this without using datetime and slicing

s = "25Aug20"

month = ''.join(char for char in s if char.isalpha())
res = s.replace(month, f' {month} ').split()
print(res)

Output:

['25', 'Aug', '20']

Comments

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.