Skip to content

Instantly share code, notes, and snippets.

@RexKang
Last active August 29, 2015 13:57
Show Gist options
  • Save RexKang/9358339 to your computer and use it in GitHub Desktop.
Save RexKang/9358339 to your computer and use it in GitHub Desktop.
Common functions for Python
#!/bin/env python
# -*- coding=utf-8 -*-
def is_ip(ip_str):
import re
pattern = r"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9] \
|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25\
[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
if re.match(pattern,ip_str):
return True
else:
return False
def has_flag(oriFlag,chkFlag):
"""Determines whether one bit field(chkFlag) is set in the oriFlag.
oriFlag and chkFlag are both int number."""
if oriFlag | chkFlag == oriFlag:
return True
else:
return False
def utc100nsstamp2string(timeStamp,format="%Y-%m-%d %H:%M:%S",timeZone=8):
"""Convert the number of 100 nano seconds from UTC like
130298165731789460 to time string like "2013-11-25 09:29:33".
timeStamp is a int or string number, like "130161080581139431".
timeZone is a int number like -8, 0,8, etc."""
from datetime import datetime,timedelta
try:
if timeStamp == "9223372036854775807":
timeString = u"Never"
# 最大值
elif timeStamp == "0":
timeString = u"NotSet"
# 没有设置
else:
ts = int(timeStamp)
ms = ts / 10
tz=timeZone*3600
timeString = (datetime(1601,1,1) + timedelta(microseconds=ms)+ \
timedelta(seconds=tz)).strftime(format)
except Exception,e:
timeString = u"utc100nsStamp2String:%s, %s" % (str(e),timeStamp)
finally:
return timeString
def string2utc100nsstamp(timeString, format="%Y-%m-%d %H:%M:%S",timeZone=8):
"""Convert the time string like "2013-11-25 09:29:33" to
number of 100 nano seconds from UTC like 130298165730000000.
timeString is a int or string number, like "130161080581139431".
timeZone is a int number like -8, 0,8, etc."""
from datetime import datetime, timedelta
try:
if timeString == u"Never":
timeStamp = "9223372036854775807"
# 最大值
if timeString == u"NotSet":
timeStamp = "0"
# 没有设置
else:
dt = datetime.strptime(timeString, format)
td = dt - datetime(1601,1,1)
tz = timeZone*3600
s = (td - timedelta(seconds=tz)).total_seconds()
timeStamp = str(int(s)) + "0000000"
except Exception,e:
timeStamp = u"utc100nsStamp2String:%s, %s" % (str(e),timeString)
finally:
return timeStamp
from datetime import datetime
def get_datestr(date=datetime.now() , format="%Y-%m-%d %H:%M:%S"):
result = date.strftime(format)
return result
def compareDateLength(date1, date2, format="%Y-%m-%d %H:%M:%S", unit="days"):
"""Compare date1 and date2, calculate and convert to the length of unit."""
from datetime import datetime
try:
unitsComputer = {"days": 86400,
"hours": 3600,
"mins": 60,
"secs": 1}
if isinstance(date1, datetime):
ds1 = date1
else:
ds1 = datetime.strptime(dateStr1, format)
if isinstance(date2, datetime):
ds2 = date2
else:
ds2 = datetime.strptime(dateStr2, format)
result = (ds1-ds2).days
except Exception,e:
result = 999
finally:
return result
def computeDate(date1, dateLength, format="%Y-%m-%d %H:%M:%S", unit="days", output='date'):
"""Calculate the date that dateStr1 + dateLength, return the result in date or string."""
from datetime import datetime, timedelta
unitsComputer = {"days": 86400,
"hours": 3600,
"mins": 60,
"secs": 1}
length = dateLength * unitsComputer[unit]
if date1:
if isinstance(date1, datetime):
ds1 = date1
else:
ds1 = datetime.strptime(dateStr1, format)
result = ds1 + timedelta(seconds=length)
else:
result = datetime.now()
if output == 'str':
result = result.strftime(format)
return result
def external_cmd(command):
import subprocess,os, sys
try:
if os.path.exists(command[0]):
proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
stdout,stderr = proc.communicate()
if proc.returncode != 0:
result = [proc.returncode, u"Error during running:%s." % stderr.decode(sys.getfilesystemencoding())]
else:
result = [0,u"%s" % stdout.decode(sys.getfilesystemencoding())]
else:
result = [2, u"Can not found the cmd."]
except Exception, e:
result = [3, u"external_cmd error:%s\n%s." % (Exception, str(e))]
finally:
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment