1. 时间
# 项目中常用的方法--时间篇
import time
from datetime import datetime, timedelta, date
# 获取今日的开始时间和结束时间
def get_today_start_end_time():
begin_date = datetime.strptime(str(date.today()), "%Y-%m-%d")
start_time = begin_date.strftime("%Y-%m-%d 00:00:00")
end_time = begin_date.strftime("%Y-%m-%d 23:59:59")
return start_time, end_time
# 获取本周开始时间和结束时间
def get_week_start_end():
now = datetime.now()
week_start = now - timedelta(days=now.weekday())
week_end = now + timedelta(days=6 - now.weekday())
week_start = week_start.strftime("%Y-%m-%d")
week_end = week_end.strftime("%Y-%m-%d")
return week_start, week_end
# 获取本周时间列表
def get_week_date_list():
# 获取当前时间
now = datetime.now()
# 判断今天周几
day_Week = datetime.now().weekday()
week_date_list = []
for i in range(7):
date = now + timedelta(days=i - day_Week)
format_date = date.strftime("%Y-%m-%d")
week_date_list.append(format_date)
return week_date_list
# 获取指定天数的时间列表
def get_date_list(days):
begin_date = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
date_list = []
begin_date = datetime.strptime(begin_date, "%Y-%m-%d")
end_date = datetime.strptime(time.strftime('%Y-%m-%d', time.localtime(time.time())), "%Y-%m-%d")
while begin_date < end_date:
date_str = begin_date.strftime("%Y-%m-%d")
date_list.append(date_str)
begin_date += timedelta(days=1)
return date_list
# 获取当前日期之前的指定天
def get_before_date(days):
before = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d 00:00:00")
before_date = datetime.strptime(before, "%Y-%m-%d %H:%M:%S")
return before_date
# 获取时间列表一年12个月
def get_month_list():
now = datetime.now()
today_year = now.year
last_year = int(now.year) - 1
today_year_months = range(1, now.month + 1)
last_year_months = range(now.month + 1, 13)
data_list_lasts = []
for last_year_month in last_year_months:
if last_year_month > 9:
pass
else:
last_year_month = "0" + str(last_year_month)
date_list = '%s-%s' % (last_year, last_year_month)
data_list_lasts.append(date_list)
data_list_todays = []
for today_year_month in today_year_months:
if today_year_month > 9:
pass
else:
today_year_month = "0" + str(today_year_month)
data_list = '%s-%s' % (today_year, today_year_month)
data_list_todays.append(data_list)
year_month = data_list_lasts + data_list_todays
return year_month
if __name__ == '__main__':
start_time, end_time = get_today_start_end_time()
print(start_time, end_time)
week_start, week_end = get_week_start_end()
print(week_start, week_end)
week_date_list = get_week_date_list()
print(week_date_list)
date_list = get_date_list(7)
print(date_list)
before_date = get_before_date(1)
print(before_date)
year_month = get_month_list()
print(year_month)
2. 加密
# 项目中常用的方法--加密篇
"""
pip install rsa
在Linux上安装pycryptodome,可以使用以下 pip 命令:
pip install pycryptodome
导入:import Crypto
在Windows上安装pycryptodomex 系统上安装则稍有不同:
pip install pycryptodomex
导入:import Cryptodome
"""
import hashlib
import rsa
from Cryptodome.Cipher import DES,AES
from Cryptodome import Random
import binascii
# 哈希加密(单向加密,非对称加密)
def hash_encryption(test_str):
"""
特点: 单向加密是指只能对明文数据进行加密,而不能解密数据。
功能: 通常用于保证数据的完整性。
特点:
不可逆:无法根据数据指纹/特征码还原原来的数据。
容易计算:从原数据计算出MD5值很容易。
抗修改性:对原数据进行任何改动,哪怕只修改1个字节,所得到的MD5值都有很大区别。
定长输出:任意长度的数据,算出的MD5值长度都是固定的。
"""
hs = hashlib.md5()
# 添加个暗号,提升复杂度(加盐)
hs.update('-(7h&ivat3uy^%9oax%**30okj=5(nx#$!uib4n^wiuoo+(0&*'.encode('utf-8'))
hs.update(test_str.encode())
print('MD5加密前为 : ' + test_str)
print('MD5加密后为 : ' + hs.hexdigest())
return hs.hexdigest()
# RSA加密
def rsa_encryption(test_str):
"""
RSA加密算法是一种非对称加密算法。在公开密钥加密和电子商业中RSA被广泛使用。
典型的如RSA等,常见方法,使用openssl ,keytools等工具生成一对公私钥对,使用被公钥加密的数据可以使用私钥来解密,反之亦然(被私钥加密的数据也可以被公钥解密) 。
在实际使用中私钥一般保存在发布者手中,是私有的不对外公开的,只将公钥对外公布,就能实现只有私钥的持有者才能将数据解密的方法。 这种加密方式安全系数很高,因为它不用将解密的密钥进行传递,从而没有密钥在传递过程中被截获的风险,而破解密文几乎又是不可能的。
但是算法的效率低,所以常用于很重要数据的加密,常和对称配合使用,使用非对称加密的密钥去加密对称加密的密钥。
"""
# 公钥
pubkey_n = '8d7e6949d411ce14d7d233d7160f5b2cc753930caba4d5ad24f923a505253b9c39b09a059732250e56c594d735077cfcb0c3508e9f544f101bdf7e97fe1b0d97f273468264b8b24caaa2a90cd9708a417c51cf8ba35444d37c514a0490441a773ccb121034f29748763c6c4f76eb0303559c57071fd89234d140c8bb965f9725'
# 十六进制‘10001’
pubkey_e = '10001'
# 需要将十六进制转换成十进制
rsa_n = int(pubkey_n, 16)
rsa_e = int(pubkey_e, 16)
# 用n值和e值生成公钥
key = rsa.PublicKey(rsa_n, rsa_e)
# 用公钥把明文加密
message = rsa.encrypt(test_str.encode(), key)
# 转化成常用的可读性高的十六进制
message = binascii.b2a_hex(message)
# 将加密结果转化回字符串并返回
print('RSA加密前为 : ' + test_str)
print('私钥 : ' + message.decode())
return message.decode()
# DES加解密(对称加密)
class DesEncryption():
"""
这种加密方式 KEY的值必须是8位,否则不支持
"""
key = b'abcduasg'
# 需要去生成一个DES对象
des = DES.new(key, DES.MODE_ECB)
BLOCK_SIZE = 32 # Bytes
def encryption(self, test_str):
text = test_str + (8 - (len(test_str) % 8)) * '='
# 加密的过程
encrypto_text = self.des.encrypt(text.encode())
print('DES加密后为 :', binascii.b2a_hex(encrypto_text))
return encrypto_text
def decrypt(self, encrypto_text):
decrypt_text = self.des.decrypt(encrypto_text)
print('DES解密后为 :', decrypt_text)
return decrypt_text
# AES加密
class AesEncryption():
"""
# 密钥key 长度必须为16(AES-128)、24(AES-192)、或32(AES-256)Bytes 长度.
"""
key = b'dhsgdysgdjwshiuw'
iv = Random.new().read(AES.block_size)
# 使用key和iv初始化AES对象, 使用MODE_CFB模式
mycipher = AES.new(key, AES.MODE_CFB, iv)
def encryption(self, test_str):
# 加密的明文长度必须为16的倍数,如果长度不为16的倍数,则需要补足为16的倍数
# 将iv(密钥向量)加到加密的密文开头,一起传输
ciphertext = self.iv + self.mycipher.encrypt(test_str.encode())
print('AES加密后数据为:', binascii.b2a_hex(ciphertext)[16:])
return ciphertext
def decrypt(self, ciphertext):
# 解密的话要用key和iv生成新的AES对象
mydecrypt = AES.new(self.key, AES.MODE_CFB, ciphertext[:16])
# 使用新生成的AES对象,将加密的密文解密
decrypttext = mydecrypt.decrypt(ciphertext[16:])
print('AES解密后数据为:', decrypttext.decode())
return decrypttext.decode()
if __name__ == '__main__':
hash_encryption('菜鸟程序员_python')
print(rsa_encryption('菜鸟程序员_python'))
des_encryption = DesEncryption()
encrypto_text = des_encryption.encryption('ertysfdhertysfdh')
decrypt_text = des_encryption.decrypt(encrypto_text)
aes_encryption = AesEncryption()
ciphertext = aes_encryption.encryption('ertysfdhertysfdh')
text = aes_encryption.decrypt(ciphertext)
3. 正则
import re # 正则匹配手机号码 def mobile_re(mobile_num): pattern = re.compile(r'(13\d|14[579]|15[^4\D]|17[^49\D]|18\d|19\d)\d{8}') phone = pattern.search(mobile_num) if phone: return phone else: return None # 正则匹配邮箱 def mailbox(email_num): pattern = re.compile(r'\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}') email = pattern.search(email_num) if email: return email else: return None # 正则匹配URL地址 def url_re(link_url): pattern = re.compile(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+') url = pattern.search(link_url) if url: return url else: return None if __name__ == '__main__': # 错误示范 print(mobile_re('5723672637')) print(mailbox('hujdchjsbdus')) print(url_re('dfghuusdhdfuiesdhdu.com')) # 正确示范 print(mobile_re('15824536217')) print(mailbox('[email protected]')) print(url_re('http://www.baidu.com'))