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

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

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

#-*- coding:utf-8 -*-
import sys
import logging reload(sys) # reload 才能调用 setdefaultencoding 方法
sys.setdefaultencoding('utf-8') # 设置 'utf-8' from cfg import config class 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 = 1000 * self.Nanosecond
self.Millisecond = 1000 * self.Microsecond
self.Second = 1000 * self.Millisecond
self.Minute = 60 * self.Second
self.Hour = 60 * 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 * 10 + int(c) - int('0')
if x < 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 *= 10
i += 1
return x, scale, s[i:] """
将小时,分钟,转换为秒
比如: 5m 转换为 300秒;5m20s 转换为320秒
time 单位支持:"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.leadingInt(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:
self.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: unkonw 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: unknow unit %s in duration %s" %(u, orig))
return 0
unit = self.unitMap[u]
if v > (1<<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)

 

使用实例:

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

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

```python

tools = TimeTool()
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. JVM(七):JVM内存结构

    JVM(七):JVM内存结构 在前几节的文章我们多次讲到 Class 对象需要分配入 JVM 内存,并在 JVM 内存中执行 Java 代码,完成对象内存的分配.执行.回收等操作,因此,如今让我们来走 ...

  2. Hive 学习之路(六)—— Hive 视图和索引

    一.视图 1.1 简介 Hive 中的视图和RDBMS中视图的概念一致,都是一组数据的逻辑表示,本质上就是一条SELECT语句的结果集.视图是纯粹的逻辑对象,没有关联的存储(Hive 3.0.0引入的 ...

  3. 【简单脚本】Linux查看配置信息

    命令比较多,统一整合了一下: 1.新建文件touch getComputerConf.sh 2.vim getComputerConf.sh 3.按i键插入,右键粘贴如下内容: #!/bin/sh e ...

  4. CI框架使用(一)

    CI框架的使用是很简单,也 是mvc模式.其中有好多类直接调用.   在使用帮助函数的时候,都需要手动加载,或者是在配置文件中加一个自动加载 $this->load->helper('ur ...

  5. Java学习笔记——设计模式之十.观察者模式

     观察者模式(Observer),定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象.这个主题对象在状态发生变化时,会通知所有观察者对象,使他们能够自动更新自己. Subject类: ...

  6. Codeblocks 批量注释与对齐快捷键的教学方法

    Ctrl+Shift+C 批量注释 Ctrl+shift+X 批量取消注释 Click Settings->Editor->KeyboardShortcuts (in the left o ...

  7. Java上机题(封装)(编写student类)

    今天帮大一的童鞋写Java上机题 题目虽然很简单,但是刚拿到题目的时候愣了一下,然后就疯狂get set QuQ 其实这是一个特别基本的封装的题目(之前实验室面试大二的时候竟然还有蛮多人不知道封装的概 ...

  8. nginx反向代理中神奇的斜线

    nginx反向代理中神奇的斜线 在进行nginx反向代理配置的时候,location和proxy_pass中的斜线会造成各种困扰,有时候多一个或少一个斜线,就会造成完全不同的结果,所以特地将locat ...

  9. 记一次SQL优化。

    程序是数据库的用户,为打造良好的用户体验,我们一直在努力. 此次介绍一个基于SQL的数据库优化.SQL的优劣对数据库的性能影响非常关键. 查询只涉及如下表结构中的三个字段.如下 开发原始SQL SEL ...

  10. 005-python-字典操作

    1. 字典 dict 用{}来表示 键值对数据 {key:value} 唯一性 键 都必须是可哈希的 不可变的数据类型就可以当做字典中的键 值 没有任何限制 dic = {'name':'alex', ...