python常用方法汇总


cmd命令

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

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)

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

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

字符串转bool

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

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

时间

字符串输出

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))))

时间比较

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

时间格式转换

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)

时间计算

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)
print(arrow.now().month) # 2
last_month = arrow.now().shift(months=-1).format("YYYYMM") # 202101
# 时间戳转字符串
time_str = datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")

补齐

#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
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值