HowardMei
2012-04-26 10:41:23 +08:00
写过一个小模块,用来将 5d 2h 3mins 这种字符串转成us/ms为单位的精确timestamp,代码太丑陋,测试也不充分,就没开源。我记得以下写法可保证 windows 7 和 ubuntu 下,得到平台无关的us级timestamp,mac上应该和ubuntu一样,s级没有平台一致性问题:
long(time.time() * 1000.0 * 1000.0 + (time.clock()*1000.0- \
int(time.clock()*1000.0))*1000.00)
不知道直接贴代码会不会很难看:
from datetime import datetime
from calendar import timegm
def nowTimeStamp(unit='us'):
"""
Returns a long integer representing UTC timestamp in 'us','ms','s'
Generate identical outputs across platforms
"""
# unit = _unify(unit) # used to unify unit strings, like 'sec' 'secs' 'seconds' 'second' to 's'
if unit == 's':
return long(time.time())
elif unit == 'ms':
return long(time.time() * 1000.0)
elif unit == 'us':
return long(time.time() * 1000.0 * 1000.0 + (time.clock()*1000.0- \
int(time.clock()*1000.0))*1000.00)
else:
raise TypeError("Not supported timestamp unit:",unit)
def getStamp(timeutc,unit='us'):
"""
Convert UTC datetime to long integer timestamp in micro/mili.seconds
usage: getStamp(utctime,unit='us') # unit could be 'us','ms','s'
"""
if isinstance(timeutc, datetime):
#unit=_unify(unit)
if unit == 's':
return long(timegm(timeutc.utctimetuple()))
elif unit == 'ms':
return long(timegm(timeutc.utctimetuple())*1000.0+ \
timeutc.microsecond/1000.0)
elif unit == 'us':
return long(timegm(timeutc.utctimetuple())*1000000.0+ \
timeutc.microsecond)
else:
raise TypeError("Not supported timestamp unit:"+unit)
else:
raise TypeError("Unknow timeutc type:",timeutc,".Use UTC time to retry.")