Manolete
Manolete

Reputation: 3517

Regex operation to modify a string

At the moment I have a string similar to:

mytime = '143456.45674'

That string is giving time in :

%HH%MM:%SS . something else

I am only interested in HH:MM:SS format so I could do:

mynewTime = mytime[0:2]+":"+mytime[2:4]+":"+mytime[4:6]
'14:34:56'

It is a bit ugly and I was wondering if there was a more elegant/efficient way of doing it. Regex perhaps?

Upvotes: 0

Views: 51

Answers (3)

wenzul
wenzul

Reputation: 4048

A regex version for fun :)

re.sub(r"(\d{2})(\d{2})(\d{2})\.\d+", r"\1:\2:\3", mytime)

Upvotes: 1

nu11p01n73R
nu11p01n73R

Reputation: 26667

If you want to do it in regex

>>> import re
>>> val=re.sub(r"\..*$", "", "143456.45674")
>>> re.sub(r"(?<=\d)(?=(\d{2})+$)", ":", val )
'14:34:56'

Upvotes: 1

georg
georg

Reputation: 214949

Looks like you're looking for a combination of strptime and strftime:

import datetime

mytime = '143456.45674'

ts = datetime.datetime.strptime(mytime, '%H%M%S.%f')
print ts.strftime('%H:%M:%S')

# 14:34:56

Upvotes: 5

Related Questions