Skip to content Skip to sidebar Skip to footer

How To Remove Multiple Characters From A String?

a = 'Sat Apr 27 2019 00:00:14 GMT+0530 (India Standard Time)' I have sample string saved to variable a. I want the output to be defined this way. The day (sat) part removed, and t

Solution 1:

Try out DateParser, Have a look below example :

import dateparser 
a = "Sat Apr 27 2019 00:00:14 GMT+0530 (India Standard Time)"
x = dateparser.parse(a) 
x.date().strftime("%d-%m-%Y") 

Output:

Parsed datetime object :

datetime.datetime(2019, 4, 27, 0, 0, 14,tzinfo=StaticTzInfo 'UTC+05:30')

The extracted output will be:

27-04-2019


Solution 2:

Here is the answer using the python standard datetime module, without using any other third-party module/library:

from datetime import datetime

dt_string = "Sat Apr 27 2019 00:00:14 GMT+0530 (India Standard Time)"

dt = datetime.strptime(' '.join(dt_string.split(' ')[:6]), '%a %b %d %Y %H:%M:%S %Z%z')

print(dt.strftime('%d-%m-%Y'))

Output

'27-04-2019'

Solution 3:

The "(India Standard Time)" is not a standard form of the Time Zone. If it "IST" then "%Z" will be the directive of the datetime format code. Assuming your all data contains "(India Standard Time)", then following is the code -

from datetime import datetime
a = "Sat Apr 27 2019 00:00:14 GMT+0530 (India Standard Time)"
date_object = datetime.strptime(a, '%a %b %d %Y %H:%M:%S GMT%z (India Standard Time)')
new_date = date_object.strftime("%d-%-m-%Y")

Alternatively, if the string 'a' contains different Time Zone name then following can be applied.

from datetime import datetime
import re

a = "Sat Apr 27 2019 00:00:14 GMT+0530 (India Standard Time)"
a= re.sub(r'\([^()]*\)', '', a)
date_object = datetime.strptime(date_string, '%a %b %d %Y %H:%M:%S GMT%z ')
new_date = date_object.strftime("%d-%-m-%Y")

Post a Comment for "How To Remove Multiple Characters From A String?"