Python implementation parseduration-supports parsing of time units in a string format, such as converting hours or minutes to seconds

Source: Internet
Author: User
Tags string format

The Python time module does not support the conversion of the number of minutes and hours in a string format to seconds, such as converting "5m" to "300" (seconds), and the conversion of "0.2h5.1m12.123s" to "1038.123" (seconds) is not supported.

However, the notation of the number of minutes or hours in a string format is useful in some configuration or user interaction.

To achieve this, by simulating the ' parseduration (S string) (duration, error) ' function in the ' time ' module of Golang, the Python code is implemented as follows:

#-*-coding:utf-8-*-import sysimport loggingreload (SYS) # Reload to invoke Setdefaultencoding method sys.setde Faultencoding (' Utf-8 ') # set ' Utf-8 ' from cfg import configclass Timetool (object): Def __init__ (self): handler = Logging. Streamhandler () formatter = logging.  Formatter ('% (asctime) s% (name) -12s% (levelname) -8s% (message) s ') Handler.setformatter (Formatter) Self.logger = Logging.getlogger ("Historyreader") Self.logger.addHandler (handler) Self.logger.setLevel (config. Log_level) self. nanosecond = 1 self. microsecond = * Self. nanosecond self.millisecond = * Self. Microsecond self. Second = Self.millisecond self. Minute = * Self. Second self. Hour = * Self. Minute Self.unitmap = {"ns": Int (self). nanosecond), "US": Int (self. microsecond), "μs": Int (self. microsecond), # u+00B5 = Micro symbol "μs": Int (self. microsecond), # U+03BC = Greek letter mu ' ms ': Int (self. Millisecond), "s": Int (self. Second), "M": Int (self. Minute), "H": Int (self. Hour),} Pass Def leadingint (self, s): X, REM, err = Int (0), str (""), "Time:bad [0-9]*" I            = 0 While I < Len (s): c = s[i] If c < ' 0 ' or C > ' 9 ': Break  #print x if x > (1 << 63-1)/10: #print "x > (1 << 63-1)/10 = =%s >%s" % (x, (1 << 63-1)/10) return 0, "", Err x = x * + int (c)-int (' 0 ') if x &lt ;  0: #print "x < 0 =%s < 0"% (x) return 0, "", Err i+=1 return x, S[i:], None def leadingfraction (self, s): x, scale, rem = Int (0), float (1),"I, overflow = 0, False while I < Len (s): c = s[i] If c < ' 0 ' or C > ' 9 ':                Break if Overflow:continue if x > (1<<63-1)/10:                overflow = True Continue y = x*10 + int (c)-int (' 0 ') if y < 0: overflow = True Continue x = y scale *= i + = 1 return x, scale,     S[i:] "" "to convert hours, minutes, seconds such as: 5m conversion to 300 seconds; 5m20s conversion to 320 seconds Time Unit support:" NS "," Us "(or" μs ")," Ms "," s "," M "," H "" ""         def parseduration (self, s): if s = = "" or Len (s) < 1:return 0 Orig = s neg = False                D = Float (0) if s! = "": if s[0] = = "-" or s[0] = = "+": Neg = s[0] = = "-" s = s[1:] if s = = "0" or S = = "": return 0 while S! = "": V, F, scale = Int (0)      , int (0), float (1)      Print "S:%s"%s # the next character must be [0-9.] If not (s[0] = = "." or ' 0 ' <= s[0] and s[0] <= ' 9 '): Self.logger.error ("Time1:invalid duration%s, s :%s "% (orig, s)) return 0 # consume [0-9]* pl = Len (s) v, s, err = SELF.L                Eadingint (s) if err! = None:self.logger.error ("time2, Invalid duration%s"%orig) return 0 pre = pl! = Len (s) # Consume (\.[            0-9]*)? Post = False if s! = "" and s[0] = = ".": s = s[1:] PL = Len (s) F, Scale, S = self.leadingfraction (s) post = pl! = Len (s) if not pre and not post:s            Elf.logger.error ("Time3, Invalid duration%s"%orig) return 0 # consume unit. i = 0 while I < Len (s): c = s[i] if c = = '. ' or ' 0 ' <= C and C <= ' 9 ': Break i+=1 if i = = 0:self.logger.error ("Time4:un            KONW unit in Duration:%s "%orig) return 0 print" s:%s, i:%s, s[:i]:%s "% (s, I, s[:i]) U = s[:i] s = s[i:] If not Self.unitMap.has_key (U): Self.logger.error ("Time5:unkno W unit%s in duration%s "% (U, orig)) return 0 unit = Self.unitmap[u] If v > (1&lt  ; <63-1)/unit:self.logger.error ("Time6:invalid duration%s"%orig) return 0 v                    *= unit if f > 0:v + = Int (float (f) * (float (unit)/scale)) if v < 0:            Self.logger.error ("Time7:invalid duration%s"%orig) return 0 D + = V  If D < 0:self.logger.error ("Time8:invalid duration%s"%orig) return 0 if Neg:d =-D        return Float (d) 

 

Usage examples:

#-*-coding:utf-8-*-from timetools import timetoolif __name__ = = "__main__":    tools = Timetool ()    s = tools. Parseduration ("1m20.123s")    print S

The default printing unit is "nanosecond", if you want to print the unit as "second", simply divide the parse result by ' Timetool.second ', for example:

"' Python

Tools = Timetool ()

s = Tools. Parseduration ("1m20.123s")
Print S/tools. Second

```

Python implementation parseduration-supports parsing of time units in a string format, such as converting hours or minutes to seconds

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.