Reputation: 583
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 this (Apr 27 2019) part converted like this "27-4-2019". I'm new to programming and any help will be appreciated.
I've a time series kind of data and the code should match for the other samples taken at multiple intervals of time with the same format above as 'a'
Upvotes: 0
Views: 179
Reputation: 519
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")
Upvotes: 1
Reputation: 1159
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'
Upvotes: 1
Reputation: 478
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
Upvotes: 2