python的time模块不支持单独将字符串格式的分钟数和小时数转换为秒,比如将“5m”转换为“300”(秒),不支持将“0.2h5.1m12.123s”转换为“1038.123”(秒)。

但是这种字符串格式的分钟数或者小时数写法,在一些配置或者用户交互中还是比较有用的。

为了实现这种功能,通过模拟golang的`time`模块中的`ParseDuration(s string) (duration, error)`函数,使用Python代码实现如下:

  1. #-*- coding:utf-8 -*-
  2. import sys
  3. import logging
  4.  
  5. reload(sys) # reload 才能调用 setdefaultencoding 方法
  6. sys.setdefaultencoding('utf-8') # 设置 'utf-8'
  7.  
  8. from cfg import config
  9.  
  10. class TimeTool(object):
  11. def __init__(self):
  12. handler = logging.StreamHandler()
  13. formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
  14. handler.setFormatter(formatter)
  15. self.logger = logging.getLogger("HistoryReader")
  16. self.logger.addHandler(handler)
  17. self.logger.setLevel(config.LOG_LEVEL)
  18. self.Nanosecond = 1
  19. self.Microsecond = 1000 * self.Nanosecond
  20. self.Millisecond = 1000 * self.Microsecond
  21. self.Second = 1000 * self.Millisecond
  22. self.Minute = 60 * self.Second
  23. self.Hour = 60 * self.Minute
  24. self.unitMap = {
  25. "ns": int(self.Nanosecond),
  26. "us": int(self.Microsecond),
  27. "µs": int(self.Microsecond), # U+00B5 = micro symbol
  28. "μs": int(self.Microsecond), # U+03BC = Greek letter mu
  29. "ms": int(self.Millisecond),
  30. "s": int(self.Second),
  31. "m": int(self.Minute),
  32. "h": int(self.Hour),
  33. }
  34. pass
  35.  
  36. def leadingInt(self, s):
  37. x, rem, err = int(0), str(""), "time: bad [0-9]*"
  38. i = 0
  39. while i < len(s):
  40. c = s[i]
  41. if c < '0' or c > '9':
  42. break
  43. #print x
  44. if x > (1 << 63-1)/10:
  45. #print "x > (1 << 63-1)/10 => %s > %s" %(x, (1 << 63-1)/10)
  46. return 0, "", err
  47. x = x * 10 + int(c) - int('0')
  48. if x < 0:
  49. #print "x < 0 => %s < 0" %(x)
  50. return 0, "", err
  51. i+=1
  52. return x, s[i:], None
  53.  
  54. def leadingFraction(self, s):
  55. x, scale, rem = int(0), float(1), ""
  56. i, overflow = 0, False
  57. while i < len(s):
  58. c = s[i]
  59. if c < '0' or c > '9':
  60. break
  61. if overflow:
  62. continue
  63. if x > (1<<63-1)/10 :
  64. overflow = True
  65. continue
  66. y = x*10 + int(c) - int('0')
  67. if y < 0:
  68. overflow = True
  69. continue
  70. x = y
  71. scale *= 10
  72. i += 1
  73. return x, scale, s[i:]
  74.  
  75. """
  76. 将小时,分钟,转换为秒
  77. 比如: 5m 转换为 300秒;5m20s 转换为320秒
  78. time 单位支持:"ns", "us" (or "µs"), "ms", "s", "m", "h"
  79. """
  80. def ParseDuration(self, s):
  81. if s == "" or len(s) < 1:
  82. return 0
  83.  
  84. orig = s
  85. neg = False
  86. d = float(0)
  87.  
  88. if s != "":
  89. if s[0] == "-" or s[0] == "+":
  90. neg = s[0] == "-"
  91. s = s[1:]
  92.  
  93. if s == "0" or s == "":
  94. return 0
  95.  
  96. while s != "":
  97. v, f, scale = int(0), int(0), float(1)
  98.  
  99. print "S: %s" %s
  100. # the next character must be [0-9.]
  101. if not (s[0] == "." or '0' <= s[0] and s[0] <= '9'):
  102. self.logger.error("time1: invalid duration %s, s:%s" % (orig, s))
  103. return 0
  104.  
  105. # Consume [0-9]*
  106. pl = len(s)
  107. v, s, err = self.leadingInt(s)
  108. if err != None:
  109. self.logger.error("time2, invalid duration %s" %orig)
  110. return 0
  111. pre = pl != len(s)
  112.  
  113. # consume (\.[0-9]*)?
  114. post = False
  115. if s != "" and s[0] == ".":
  116. s = s[1:]
  117. pl = len(s)
  118. f, scale, s = self.leadingFraction(s)
  119. post = pl != len(s)
  120. if not pre and not post:
  121. self.logger.error("time3, invalid duration %s" %orig)
  122. return 0
  123.  
  124. # Consume unit.
  125. i = 0
  126. while i < len(s):
  127. c = s[i]
  128. if c == '.' or '0' <= c and c <= '9':
  129. break
  130. i+=1
  131. if i == 0:
  132. self.logger.error("time4: unkonw unit in duration: %s" %orig)
  133. return 0
  134. print "s:%s, i:%s, s[:i]:%s" %(s, i, s[:i])
  135. u = s[:i]
  136. s = s[i:]
  137. if not self.unitMap.has_key(u):
  138. self.logger.error("time5: unknow unit %s in duration %s" %(u, orig))
  139. return 0
  140. unit = self.unitMap[u]
  141. if v > (1<<63-1)/unit:
  142. self.logger.error("time6: invalid duration %s" %orig)
  143. return 0
  144. v *= unit
  145. if f > 0 :
  146. v += int(float(f) * (float(unit) / scale))
  147. if v < 0:
  148. self.logger.error("time7: invalid duration %s" %orig)
  149. return 0
  150. d += v
  151. if d < 0 :
  152. self.logger.error("time8: invalid duration %s" %orig)
  153. return 0
  154.  
  155. if neg :
  156. d = -d
  157. return float(d)

 

使用实例:

  1. #-*- coding:utf-8 -*-
  2. from timeTools import TimeTool
  3.  
  4. if __name__ == "__main__":
  5. tools = TimeTool()
  6. s = tools.ParseDuration("1m20.123s")
  7. print s

默认打印单位是“Nanosecond”,如果想要打印单位为“second”的话,只需要将parse结果除以`TimeTool.Second`即可,例如:

```python

  1. tools = TimeTool()
  1. s = tools.ParseDuration("1m20.123s")
    print s/tools.Second

```

Python实现ParseDuration-支持解析字符串格式的时间单位,例如将小时或者分钟数转换为秒的更多相关文章

  1. Python_time库_特定字符串格式的时间、struct_time、时间戳的处理

    time库 时间戳:格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数. # time.strptime(),功能:将特定字符串格 ...

  2. js把字符串格式的时间转换成几秒前、几分钟前、几小时前、几天前等格式

    最近在做项目的时候,需要把后台返回的时间转换成几秒前.几分钟前.几小时前.几天前等的格式:后台返回的时间格式为:2015-07-30 09:36:10,需要根据当前的时间与返回的时间进行对比,最后显示 ...

  3. 机器学习实战ch04 关于python版本所支持的文本格式问题

    函数定义中: def spamTest(): docList=[]; classList = []; fullText =[] for i in range(1,26):# print('cycle ...

  4. 让IIS支持解析.json格式文件

    原文出处链接及本声明. 原文链接:https://blog.csdn.net/jumtre/article/details/72630730 1.IIS内点击网站进入网站主页设置界面: 2.双击MIM ...

  5. 判断库中为字符串格式的时间是否为最近三个月(Java)

    今天分享一个问题,就是标题中提到的问题,今天在调用一个接口的时候,发现调用到的数据的时间格式为字符串类型,我有点蒙圈,于是,我就百度解决了这个问题,同时在这里记录一下,为了之后不再蒙圈::: 首先需要 ...

  6. js 字符串格式化为时间格式

    首先介绍一下我遇到的坑,找了几个关于字符串转时间的,他们都可以就我用的时候不行. 我的原因,我的字符串是MYSQL拿出来的不是标准的时间格式,是不会转成功的. 解决思路:先将字符串转为标准时间格式的字 ...

  7. js获取此刻时间或者把日期格式时间转换成字符串格式的时间

    getTime(val){ if (val&val instanceof Date){ d = val; }else{ d = new Date(); }; var year = d.getF ...

  8. python教程(六)·字符串

    我们已经学习了字符串的使用方法,我们还学习了使用索引和分片操作字符串,经历了这么长的时间,相信大家也有所掌握:本节将讨论并学习字符串的格式化与字符串的常用方法 字符串格式化 字符串是序列的一种,所以所 ...

  9. Python中的文档字符串作用

    文档字符串是使用一对三个单引号 ''' 或者一对三个双引号 """来包围且没有赋值给变量的一段文字说明(如果是单行且本身不含引号,也可以是单引号和双引号), 它在代码执行 ...

随机推荐

  1. 浅谈jpa、hibernate与spring data jpa三者之间的关系

    1.解释hibernate之前先了解下什么是orm,orm是object relation mapping,即对象关系映射,object可以理解成java实体类Entity,relation是关系型数 ...

  2. 【转载】Chrome使用自定义协议打开本地程序并运行IE打开网页

    部分内容转载自: http://blog.sina.com.cn/s/blog_e2b8213a0102wqby.html 项目中遇到某需求:chorme要运行IE并打开网页.解决方案之一就是通过自定 ...

  3. sentinel 滑动窗口统计机制

    sentinel的滑动窗口统计机制就是根据当前时间,获取对应的时间窗口,并更新该时间窗口中的各项统计指标(pass/block/rt等),这些指标被用来进行后续判断,比如限流.降级等:随着时间的推移, ...

  4. 一次性搞清楚线上CPU100%,频繁FullGC排查套路

    “ 处理过线上问题的同学基本上都会遇到系统突然运行缓慢,CPU 100%,以及 Full GC 次数过多的问题. 当然,这些问题最终导致的直观现象就是系统运行缓慢,并且有大量的报警. 本文主要针对系统 ...

  5. 《菜鸟也要学会C》-和大家聊一聊

    简介 为什么要出本系列作品? 怎么学好C? 学完这套课程后,我的编程会怎么样? 1.1为什么要出本系列作品? 随着大部分人喜欢编程,大部分人都有一个毛病,就是想要急切的学完编程.其实这种思想是错误的, ...

  6. mysql 正确清理binlog日志的两种方法

    前言: MySQL中的binlog日志记录了数据库中数据的变动,便于对数据的基于时间点和基于位置的恢复,但是binlog也会日渐增大,占用很大的磁盘空间,因此,要对binlog使用正确安全的方法清理掉 ...

  7. Python 3网络爬虫开发实战》中文PDF+源代码+书籍软件包

    Python 3网络爬虫开发实战>中文PDF+源代码+书籍软件包 下载:正在上传请稍后... 本书书籍软件包为本人原创,在这个时间就是金钱的时代,有些软件下起来是很麻烦的,真的可以为你们节省很多 ...

  8. header 无法实现跳转

    错误:Warning: Cannot modify header information - headers already sent by (output started at 方法:“php.in ...

  9. HDU 3938:Portal(并查集+离线处理)

    http://acm.hdu.edu.cn/showproblem.php?pid=3938 Portal Problem Description   ZLGG found a magic theor ...

  10. Linux命令学习-ls命令

    Linux中,ls命令的全称是list,主要作用是列出当前目录下的清单. 列出Linux根目录下的所有目录 ls / 列出当前目录下所有文件夹和文件 ls 列出当前目录下所有文件夹和文件(包括以&qu ...