简体   繁体   中英

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?

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

一个有趣的正则表达式版本:)

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

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM