当前位置:   article > 正文

python常用方法汇总

python常用方法


cmd命令

os.system('chcp 65001') #cmd编码问题处理
os.system('git clone ...')
  • 1
  • 2

re正则

import re
p = re.compile('[0-9]+')
m = p.match('1abcde2')
if m:
 print 'Match found: ', m.group()
else:
 print 'No match'
p.findall('11aa22bb')
p.sub("","11aa22bb")
re.sub((rgExp, replaceText, str)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

生成指定长度,指定元素,随机字符串

"".join(random.sample('zyxwvutsrqponmlkjihgfedcba0123456789',11))
  • 1

字符串转bool

使用bool()只能将:空字符串,(),[],{},None,0转为False,其它为True,
所以建议使用如下方法:

def str2bool(v)
    return v.lower() in ("yes","true","correct","right",
    "on","open","okay","ok","y","t","1")
  • 1
  • 2
  • 3

时间

字符串输出

str(datetime.datetime.now()).split(".")[0]
# '2020-06-23 09:37:59'
datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
# '2020_06_23_09_38_01'
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 
# '2020-06-23 09:41:22'
# 从float转时间(UTC)
print (time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(float(63650571169.50261)))float转时间(local)
print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(float(63650571169.50261))))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

时间比较

timestamp_specify=time.mktime(time.strptime("2021/04/15","%Y/%m/%d"))
timestamp_now=time.time() //当前时间timestamp
if time.time() > time.mktime(time.strptime("2021-04-15 12:30:00", "%Y-%m-%d %H:%M:%S")):
	return
  • 1
  • 2
  • 3
  • 4

时间格式转换

print(time.strftime("%Y-%m-%d %H:%M:%S", time.strptime("2021_03_10_11_12_13", "%Y_%m_%d_%H_%M_%S")))
# 2021-03-10 11:12:13
# 转换成时间戳
timestamp = time.mktime(timeArray)
  • 1
  • 2
  • 3
  • 4

时间计算

today = datetime.date.today()
first_day = today.replace(day=1)
last_month = (first_day - datetime.timedelta(days=1)).strftime("%Y%m")
one_year_ago = self.today - relativedelta(years=1)
  • 1
  • 2
  • 3
  • 4
print(arrow.now().month) # 2
last_month = arrow.now().shift(months=-1).format("YYYYMM") # 202101
  • 1
  • 2
# 时间戳转字符串
time_str = datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")
  • 1
  • 2

补齐

#rjust,右对齐,左补空格
s = "123".rjust(5)
assert s == " 123"
#左补0
s.rjust(5,"0")
#也可用zfill左补0
s.zfill(width)
#ljust,左对齐,右补空格
s = "123".ljust(5)
assert s == "123 "
#center,字符串居中,左右补空格
s = "123".center(5)
assert s == " 123 "
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号