Reputation: 93
Given a text :
start_KA03MM7155_RKMS121MI4-4.21005_NEW_end, 2018-01-02 09:48:23
.
How do i extract 2018-01-02
as 020118
in a variable and 09:48:23
as 094823
in another variable using python?
Upvotes: 1
Views: 449
Reputation: 1365
Quick and dirty way,
date = re.sub('-', '', re.findall('\d{4}-\d{2}-\d{2}',a)[0]) # '20180102'
time = re.sub(':', '', re.findall('\d{2}:\d{2}:\d{2}',a)[0]) # '094823'
Upvotes: 2
Reputation: 1272
if your date in the string follows YYYY-MM-DD or YYYY-MM-DD pattern,
code to extract date field
import re
text = 'start_KA03MM7155_RKMS121MI4-4.21005_NEW_end, 2018-01-02 09:48:23'
result = re.search('(\d{4}-\d{2}-\d{2})', text).group(0)
print('result: ', result)
result: 2018-01-02
then you can manipulate string to get desired output, for your case
split_data = d.split('-') #split the string
date_pattern = split_data[-1] + split_data[-2] + split_data[-3][-2:]
print('date Pattern: ', date_pattern)
date Pattern: 020118
with a small change in regex pattern you can time
time_pattern = re.search('(\d{2}:\d{2}:\d{2})', a).group(0).replace(':', '')
print('time_pattern: ', time_pattern)
time_pattern: 094823
Brief Explanation:
\d
looks for digits
\d{4}
matches 4 digits
(\d{4}-\d{2}-\d{2})
looks for a group having (4 digits)-(2 digits)-(2 digits)
to know more about regex you can follow the official link
Upvotes: 2