Date String Formatting In Python

Viewed 40

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']
4 Answers

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

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.

You can also use Regex

Ex:

import re

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

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