【05】Python 标准模块:random、os、time、hashlib加密 第三方模块:excel、数据库 列表生成式、修改pip源、AES加密、日期、时间、字符串相互转换
1 模块分类
- 标准模块,不需要你单独安装,python自带的模块
- 第三方模块
- 自己写的python 一个python文件就是一个模块
2 random模块
2.1 随机取元素
1 import random 2 print(random.randint(10,99)) #随机取一个整数 顾头又顾尾 3 print(random.uniform(1,9))#取一个小数 4 print(random.choice('abcdefg'))#随机取一个元素,列表、字符串均可传入 5 stus = ['xiaojun','hailong','yangfan','tanailing','yangyue','cc'] 6 print(random.sample(stus,2)) #返回List,随机取N个元素,列表、字符串均可传入
1 2 3 4 5 | #运行结果 80 4.679334209523862 c [ 'cc' , 'tanailing' ] |
2.2 洗牌
1 import random 2 l = list(range(1,10)) 3 print('洗牌之前的',l) 4 print(random.shuffle(l))#洗牌,没有返回值(类似于List的其他方法),只能传入list 5 print('洗牌之后的',l)
1 2 3 4 | #运行结果 洗牌之前的 [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] None 洗牌之后的 [ 3 , 4 , 5 , 8 , 9 , 6 , 1 , 7 , 2 ] |
3 OS模块
3.1 文件文件夹
1 import os 2 os.rename(old,new)#重命名 3 os.remove(f)#删除文件 4 os.mkdir('japan/tokyou') #创建文件夹,父目录不存在会报错 5 os.makedirs('japan/tokyou') #父目录不存在的时候会帮你创建 6 os.removedirs('china')#只能删除空文件夹,否则会报错 7 print(os.listdir())#显示该目录下面的所有文件和文件夹 8 print(os.path.isdir('china'))#判断是否是文件夹,不存在也返回False 9 print(os.path.isfile('china'))#判断是否是文件,不存在也返回False 10 print(os.path.exists('china'))#判断文件或者文件夹是否存在
3.2 其他操作
1 import os 2 res = os.system('ipconfig')#执行操作系统命令,返回值为“退出状态码” 3 print('os.system()结果',res) 4 res = os.popen('ipconfig')#用来执行操作系统命令,返回值为脚本执行过程中的输出内容,返回的是file对象 5 print('获取脚本执行过程中的返回值:',res.read()) 6 7 print('拼路径',os.path.join('china','beijing','haidian','changping','a.py'))#拼路径,兼容不同系统 8 res = os.path.split(r'china\beijing\haidian\西二旗\b.py')#用来分割文件名和路径 9 print('分割文件名和路径:',res) 10 res = os.path.dirname(r'china\beijing\haidian\西二旗\b.py')#取父目录,参数不能只写文件名 11 print('取父目录',res) 12 res = os.path.abspath('test.py') #取绝对路径,后面可以只跟同目录下的文件名 13 print(os.path.getsize('test.py'))#文件大小,单位是字节 14 print(os.getcwd())#取当前的目录 15 print(os.chdir(r'D:\我的文档\day6'))#进入到哪个目录下,没有返回值 16 print(os.getcwd())#取当前的目录
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | #执行结果 Windows IP ���� ���߾����������� ������������: �����ض��� DNS �� . . . . . . . : IPv4 ��ַ . . . . . . . . . . . . : 192.168 . 1.100 ...... os.system()结果 0 获取脚本执行过程中的返回值: Windows IP 配置 无线局域网适配器 无线网络连接: 连接特定的 DNS 后缀 . . . . . . . : IPv4 地址 . . . . . . . . . . . . : 192.168 . 1.100 子网掩码 . . . . . . . . . . . . : 255.255 . 255.0 ...... 拼路径 china\beijing\haidian\changping\a.py 分割文件名和路径: ( 'china\\beijing\\haidian\\西二旗' , 'b.py' ) 取父目录 china\beijing\haidian\西二旗 1542 E:\PycharmProjects\test\day6 None D:\我的文档\day6 Process finished with exit code 0 |
3.3 目录遍历
1 import os 2 res = os.walk(r'E:\PycharmProjects\test\day6\china') 3 for cur_path, dirs, files in res: 4 print('当前目录', cur_path) 5 print('当前目录下所有文件', files) 6 print('当前目录下所有文件夹', dirs)
1 2 3 4 5 6 7 8 9 10 11 12 13 | #运行结果 当前目录 E:\PycharmProjects\test\day6\china 当前目录下所有文件 [] 当前目录下所有文件夹 [ 'beijing' ] 当前目录 E:\PycharmProjects\test\day6\china\beijing 当前目录下所有文件 [] 当前目录下所有文件夹 [ 'haidian' ] 当前目录 E:\PycharmProjects\test\day6\china\beijing\haidian 当前目录下所有文件 [] 当前目录下所有文件夹 [ '西二旗' ] 当前目录 E:\PycharmProjects\test\day6\china\beijing\haidian\西二旗 当前目录下所有文件 [] 当前目录下所有文件夹 [] |
例1:
1 #获取E盘下有多少个Python文件 2 import os 3 res = os.walk(r'E:') 4 count = 0 5 for cu_path, dirs, files in res: 6 for f in files: 7 if f.endswith('.py'): 8 #if '.py' in f: 方法二 9 count += 1 10 print(count)
例2:
1 #查询指定文件的目录 2 import os 3 def find_file(path,keyword): 4 res = os.walk(path) 5 for cur_path, dirs, files in res: 6 for file_name in files: 7 if keyword in file_name: 8 print('该文件在 %s下面' %cur_path) 9 find_file('D:','a.py')
4 time模块
4.1 概念
- 格式化好的时间: 2018-09-15 14:08:53
- 时间戳:从计算机诞生那天到现在过了多少秒
1 import time 2 res1 = time.strftime('%y%m%d')#取当前的格式化日期,会按指定格式显示 3 res2 = time.strftime('%Y-%m-%d %H:%M:%S') #取当前的格式化时间,注意大小写 4 res3 = time.time() #获取当前时间戳 毫秒级 5 res4 = int(res3)#时间戳取到秒为止 6 7 print('当前日期',res1) 8 print('当前时间',res2) 9 print('当前时间戳',res3) 10 print('当前时间戳(秒)',res4)
1 2 3 4 5 | #运行结果 当前日期 180919 当前时间 2018 - 09 - 19 21 : 13 : 26 当前时间戳 1537362806.048166 当前时间戳(秒) 1537362806 |
4.2 格式化时间-->时间戳
- 格式化时间转换为时间戳时,要先转换成时间元组,然后从时间元组转换成时间戳
1 import time 2 time_tuple = time.strptime('2038-08-29 19:23:59','%Y-%m-%d %H:%M:%S')#把格式化好的时间转成时间元组 3 print(time.mktime(time_tuple))#时间元组转换成时间戳
1 2 | #运行结果 2166693839.0 |
- 格式化时间转换成时间戳方法
1 #格式化时间转换成时间戳方法 2 import time 3 def str_to_timestamp(time_str = None, format = '%Y-%m-%d %H%M%S'): 4 if time_str: 5 time_tuple = time.strptime(time_str, format)#转换成时间元组 6 timestamp = time.mktime(time_tuple)#转换成时间戳 7 else: 8 timestamp = time.time()#获取当前时间戳 9 return int(timestamp) 10 print(str_to_timestamp()) 11 print(str_to_timestamp('2039-11-23 175123'))
1 2 3 | #运行结果 1537364314 2205654683 |
4.3 时间戳-->格式化时间
- 时间戳转换成格式化时间,也要先转换成时间元组,然后从时间元组再转换成格式化时间
1 import time 2 res = time.gmtime(20198312)#转换成时间元组 3 res2 = time.strftime('%Y-%m-%d %H:%M:%S',res)#时间元组转换成格式化时间 4 print(res2) 5 6 res = time.gmtime(time.time())#是把时间戳转时间元组的,标准时区 7 res = time.localtime(time.time())#是把时间戳转时间元组的,当前时区 8 res2 = time.strftime('%Y-%m-%d %H:%M:%S',res) 9 print(res2)
1 2 3 | #运行结果 1970 - 08 - 22 18 : 38 : 32 2018 - 09 - 19 21 : 54 : 39 |
- 时间戳转换成格式化时间方法
1 import time 2 def timestamp_to_strtime(timestamp=None,format='%Y-%m-%d %H:%M:%S'): 3 #这个函数是用来把时间戳转成格式化好的时间 4 #如果不传时间戳的话,那么就返回当前的时间 5 if timestamp: 6 time_tuple = time.localtime(timestamp) 7 str_time = time.strftime(format,time_tuple) 8 else: 9 str_time = time.strftime(format) 10 return str_time 11 12 #当前的时间-3天 13 three = str_to_timestamp() - (3*24*60*60) #当前时间转换成时间戳-3天 14 res = timestamp_to_strtime(three) 15 print('3天前的时间是',res)
4.4 strftime和strptime方法
1 import time 2 #strftime方法 3 res = time.strftime('%y%m%d') #取当前的格式化日期 4 res = time.strftime('%Y-%m-%d %H:%M:%S',time_tuple) #将时间元组转换成格式化时间 5 #strptime方法 6 time_tuple = time.strptime('19920102', '%Y%m%d')#把格式化好的时间转成时间元组
5 hashlib加密
5.1 加密
1 import hashlib 2 #python2中是md5 即import md5 3 password = '123456' 4 print(password.encode()) #对password进行编码,返回bytes字符串,这样才能加密 5 m1 = hashlib.md5(password.encode()) #MD5加密,不可逆,网上的解码都是利用撞库来实现的 6 m2 = hashlib.sha1(password.encode()) #sha1加密 7 m3 = hashlib.sha224(password.encode()) 8 m4 = hashlib.sha256(password.encode()) 9 print(m1.hexdigest()) #十六进制摘要 10 print(m2.hexdigest()) 11 print(m3.hexdigest()) 12 print(m4.hexdigest())
1 2 3 4 5 6 | #运行结果 b '123456' e10adc3949ba59abbe56e057f20f883e 7c4a8d09ca3762af61e59520943dc26494f8941b f8cdb04495ded47615258f9dc6a3f4707fd2405434fefc3cbf4ef4e6 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92 |
注:不知道变量有哪些方法,可用dir()查看
print(dir(m))
5.2 加盐
1 def my_md5(s:str,salt=None): 2 #salt是盐值 3 s = str(s) 4 if salt: 5 s = s+salt 6 m = hashlib.md5(s.encode()) 7 return m.hexdigest()
6 第三方模块
安装方法
1、pip install xxxx
2、.whl文件
pip install c:/user/niuhanyang/desktop/xxx.whl
3、.tar.gz
1、先解压
2、解压之后在命令行里面进入到这个目录下
3、执行python setup.py install
7 xpinyin
1 import xpinyin 2 s = xpinyin.Pinyin() 3 print(s.get_pinyin('小军',''))
1 2 | #运行结果 xiaojun |
1 import xpinyin 2 p = xpinyin.Pinyin() 3 print(p.get_initials('上海','')) 4 print(p.get_initials('上海','').lower()) 5 print(p.get_initials('上海','_')) 6 print(p.get_initials('上海'))
1 2 3 4 5 | #运行结果 SH sh S_H S - H |
8 pymysql
8.1 参数说明
pymysql.Connect()参数说明 host( str ): MySQL服务器地址 port( int ): MySQL服务器端口号 user( str ): 用户名 passwd( str ): 密码 db( str ): 数据库名称 charset( str ): 连接编码 connection对象支持的方法 cursor() 使用该连接创建并返回游标 commit() 提交当前事务 rollback() 回滚当前事务 close() 关闭连接 cursor对象支持的方法 execute(op) 执行一个数据库的查询命令 fetchone() 取得结果集的下一行 fetchmany(size) 获取结果集的下几行 fetchall() 获取结果集中的所有行 rowcount() 返回数据条数或影响行数 close() 关闭游标对象 |
8.2 查
1 import pymysql 2 host='1**.**.*.40' 3 user='jxz' 4 password='123456' #密码只能是字符串 5 db='jxz' 6 port=3306#端口号只能写int类型 7 charset='utf8'#只能写utf8,不能写utf-8 8 conn = pymysql.connect(host=host,password=password, 9 user=user,db=db,port=port, 10 charset=charset,autocommit=True 11 )#建立连接 12 cur= conn.cursor() #建立游标 13 sql='select * from app_myuser limit 5;' 14 cur.execute(sql)#执行sql语句 15 print(cur.description)#获取这个表里面的所有字段信息 16 print('fetchone:',cur.fetchone())#查询时获取结果集的第一行数据,返回一个元组,该元组元素即为第一行数据,如果没有则为None 17 print('fetchall:',cur.fetchall())#查询时获取结果集中的所有行,一行构成一个元组,然后再将这些元组返回(即嵌套元组) 18 print('fetchone:',cur.fetchone())#结果是None,类似于文件读写时的指针,指针已在最下面 19 cur.close() 20 conn.close()
1 2 3 4 5 | #执行结果 (( 'id' , 3 , None , 11 , 11 , 0 , False ), ( 'username' , 253 , None , 32 , 32 , 0 , False ), ( 'passwd' , 253 , None , 32 , 32 , 0 , False ), ( 'is_admin' , 2 , None , 6 , 6 , 0 , False )) fetchone: ( 1145 , 'liuyana001' , '123456' , 1 ) fetchall: (( 1146 , 'xd' , '123456' , 1 ), ( 1147 , '颜无柳' , '1' , 1 ), ( 1148 , 'pythonnjf' , '123456' , 1 ), ( 1149 , 'gebilaowang' , '123456' , 1 )) #指针已在第二条,所以显示第二~第五条 fetchone: None |
8.3 增
1 import pymysql 2 conn = pymysql.connect(host=host,password=password, 3 user=user,db=db,port=port, 4 charset=charset,autocommit=True 5 )#建立连接 6 cur= conn.cursor() #建立游标 7 sql='insert into app_myuser (username,passwd,is_admin) VALUE ("p20180921","123456",1);' 8 cur.execute(sql)#执行sql语句 9 print(cur.description)#insert返回值为None 10 print('fetchall:',cur.fetchall())#insert无返回值 11 # conn.commit()#提交,connect()方法中autocommit=True,则不需要提交 12 cur.close() 13 conn.close()
1 2 3 | #运行结果 None fetchall:() |
8.4 删
1 import pymysql 2 conn = pymysql.connect(host=host,password=password, 3 user=user,db=db,port=port, 4 charset=charset,autocommit=True 5 )#建立连接 6 cur= conn.cursor() #建立游标 7 sql='delete from app_myuser where username ="p20180921";' 8 cur.execute(sql)#执行sql语句 9 print(cur.description)#insert返回值为None 10 print('fetchall:',cur.fetchall())#delete无返回值 11 # conn.commit()#提交,connect()方法中autocommit=True,则不需要提交 12 cur.close() 13 conn.close()
1 2 3 | #运行结果 None fetchall: () |
8.5 改
1 import pymysql 2 conn = pymysql.connect(host=host,password=password, 3 user=user,db=db,port=port, 4 charset=charset,autocommit=True 5 )#建立连接 6 cur= conn.cursor() #建立游标 7 sql='update app_myuser set passwd = "new123456" where username ="test123";' 8 cur.execute(sql)#执行sql语句 9 print(cur.description)#insert返回值为None 10 print('fetchall:',cur.fetchall())#update无返回值 11 # conn.commit()#提交,connect()方法中autocommit=True,则不需要提交 12 cur.close() 13 conn.close()
1 2 3 | #运行结果 None fetchall: () |
8.6 例
#方法1 import pymysql def my_db(ip,user,password,db,sql,port=3306,charset='utf8'): conn = pymysql.connect( host=ip,user=user,password=password, db=db, port=port,charset=charset,autocommit=True ) cur = conn.cursor() cur.execute(sql) res = cur.fetchall() cur.close() conn.close() return res
#方法2 import pymysql def my_db2(sql): conn = pymysql.connect( host='1*.*.*.*0',user='jxz',password='123456', db='jxz', port=3306,charset='utf8',autocommit=True ) pass
sql可使用参数化查询:
1 row_count=cursor.execute("select user,pass from tb7 where user=%s and pass=%s",(user,passwd)) #参数化sql语句
1 sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)" 2 cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
8.7 executemany()方法
executemany()方法,在一次数据库的IO操作中,可以插入多条记录。在大量数据传输中,它相比于execute()方法,不仅方便,而且提高了效率。
executemany('sql',data_list) #sql就是我们要执行的sql语句 #data_list是一个包含多行数据的列表,每行数据可以用列表[]包裹,也可以用元祖()包裹 #比如:[(1, '小明', 10), (2, '小白', 20)] #或:[['Ada', 100, 92], ['Jack', 89, 97]]
import pymysql data01 = [['1', 'Ada', '23'], ['2', 'Black', '19'], ['3', 'Tim', '30']] data02 = [('4', 'Green', '25'), ('5', 'Bai', '32')] db = pymysql.connect(host = '127.0.0.1', port = 3306, user = 'root', password = '19970928', database = 'stu', charset = 'utf8') cur = db.cursor() try: sql = 'insert into test_table \ values(%s, %s, %s);' cur.executemany(sql, data01) cur.executemany(sql, data02) db.commit() print('成功...') except Exception as e: db.rollback() print("错误信息:", e) cur.close() db.close()
9 Excel
9.1 xlwt写
1 import xlwt 2 book = xlwt.Workbook() 3 sheet = book.add_sheet('sheet1') 4 sheet.write(0,0,'id')#指定行和列写内容 5 sheet.write(0,1,'username') 6 sheet.write(0,2,'password') 7 sheet.write(1,0,'1') 8 sheet.write(1,1,'niuhanyang') 9 sheet.write(1,2,'123456') 10 book.save('stu01.xls')# .xlsx 写入excel文件
例:
1 import xlwt 2 stus = [ 3 [1,'njf','1234'], 4 [2,'xiaojun','1234'], 5 [3,'hailong','1234'], 6 [4,'xiaohei','1234'] 7 ] 8 book = xlwt.Workbook() 9 sheet = book.add_sheet('sheet01') 10 line = 0 #控制的是行 11 for stu in stus:#行 12 col = 0#控制列 13 for s in stu: 14 sheet.write(line,col,s) 15 col+=1 16 line+=1 17 book.save('stu02.xls')# .xlsx
9.2 xlrd读
1 import xlrd 2 book = xlrd.open_workbook('stu.xls')
sheetnames = book.sheet_names() #得到sheetname:['222', '111']
3 sheet = book.sheet_by_index(0) 4 # sheet = book.sheet_by_name('sheet1') 5 print(sheet.nrows) #excel里面有多少行 6 print(sheet.ncols) #excel里面有多少列 7 8 print(sheet.cell(0,0).value) #获取到指定单元格的内容 9 print(sheet.cell(0,1).value) #获取到指定单元格的内容 10 11 print("row_values: ",sheet.row_values(0))#获取到整行的内容 12 print("col_values: ",sheet.col_values(0))#获取到整列的内容 13 14 for i in range(sheet.nrows):#循环获取每行的内容 15 print(i+1,'行:',sheet.row_values(i))
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #运行结果 9 3 1.0 njf row_values: [ 1.0 , 'njf' , '1234' ] col_values: [ 1.0 , 2.0 , 3.0 , 4.0 , 4.0 , 4.0 , 4.0 , 4.0 , 4.0 ] 1 行: [ 1.0 , 'njf' , '1234' ] 2 行: [ 2.0 , 'xiaojun' , '1234' ] 3 行: [ 3.0 , 'hailong' , '1234' ] 4 行: [ 4.0 , 'xiaohei' , '1234' ] 5 行: [ 4.0 , 'xiaohei' , '1234' ] 6 行: [ 4.0 , 'xiaohei' , '1234' ] 7 行: [ 4.0 , 'xiaohei' , '1234' ] 8 行: [ 4.0 , 'xiaohei' , '1234' ] 9 行: [ 4.0 , 'xiaohei' , '1234' ] |
9.3 xlutils 改
1 import xlrd 2 from xlutils import copy 3 book = xlrd.open_workbook('stu.xls')#先用xlrd打开一个Excel 4 new_book = copy.copy(book)#然后用xlutils里面的copy功能,复制一个Excel 5 sheet = new_book.get_sheet(0)#获取sheet页 6 sheet.write(0,1,'倪菊芳') 7 sheet.write(1,1,'白小军') 8 new_book.save('stu.xls')
10 列表生成式
1 res = [ str(i).zfill(2) for i in range(1,34)] 2 l = [ i for i in range(10) ] 3 print(l) 4 print(res)
1 2 3 | #运行结果 [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] [ '01' , '02' , '03' , '04' , '05' , '06' , '07' , '08' , '09' , '10' , '11' , '12' , '13' , '14' , '15' , '16' , '17' , '18' , '19' , '20' , '21' , '22' , '23' , '24' , '25' , '26' , '27' , '28' , '29' , '30' , '31' , '32' , '33' ] |
11 AES加密
AES-128-ECB pkcs5padding
pip install pycryptodome==3.9.8
1 import base64 2 from Crypto.Cipher import AES 3 4 5 # AES-128-ECB-PKCS5 6 class EncryptDate: 7 def __init__(self, key): 8 self.key = key.encode("utf-8") # 初始化密钥 9 self.length = AES.block_size # 初始化数据块大小 10 self.aes = AES.new(self.key, AES.MODE_ECB) # 初始化AES,ECB模式的实例 11 # 截断函数,去除填充的字符 12 self.unpad = lambda date: date[0:-ord(date[-1])] 13 14 def pad(self, text): 15 """ 16 #填充函数,使被加密数据的字节码长度是block_size的整数倍 17 """ 18 count = len(text.encode('utf-8')) 19 add = self.length - (count % self.length) 20 entext = text + (chr(add) * add) 21 return entext 22 23 def encrypt(self, encrData): # 加密函数 24 res = self.aes.encrypt(self.pad(encrData).encode("utf8")) 25 msg = str(base64.b64encode(res), encoding="utf8") 26 return msg 27 28 def decrypt(self, decrData): # 解密函数 29 res = base64.decodebytes(decrData.encode("utf8")) 30 msg = self.aes.decrypt(res).decode("utf8") 31 return self.unpad(msg) 32 33 if __name__ == '__main__': 34 eg = EncryptDate("HAOHUAN_PASSWORD") # 这里密钥的长度必须是16的倍数 35 data = '淘宝网' 36 res = eg.encrypt(str(data)) 37 print(res) 38 print(eg.decrypt(res))
12 日期、时间、字符串相互转换
dateTime转换为date
如果要比较,可以将dateTime转换为date,date不能直接转换为dateTime
1 import datetime 2 dateTime_p = datetime.datetime.now() 3 date_p = dateTime_p.date() 4 print(dateTime_p) #2019-01-30 15:17:46.573139 5 print(date_p) #2019-01-30
date转换为str
#!/usr/bin/env python3 import datetime date_p = datetime.datetime.now().date() str_p = str(date_p) print(date_p,type(date_p)) #2019-01-30 <class 'datetime.date'> print(str_p,type(str_p)) #2019-01-30 <class 'str'>
datetime格式化
import datetime datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S" )
strftime参数:
strftime(format[, tuple]) -> string
将指定的struct_time(默认为当前时间),根据指定的格式化字符串输出
python中时间日期格式化符号: %y 两位数的年份表示(00-99) %Y 四位数的年份表示(000-9999) %m 月份(01-12) %d 月内中的一天(0-31) %H 24小时制小时数(0-23) %I 12小时制小时数(01-12) %M 分钟数(00=59) %S 秒(00-59) %a 本地简化星期名称 %A 本地完整星期名称 %b 本地简化的月份名称 %B 本地完整的月份名称 %c 本地相应的日期表示和时间表示 %j 年内的一天(001-366) %p 本地A.M.或P.M.的等价符 %U 一年中的星期数(00-53)星期天为星期的开始 %w 星期(0-6),星期天为星期的开始 %W 一年中的星期数(00-53)星期一为星期的开始 %x 本地相应的日期表示 %X 本地相应的时间表示 %Z 当前时区的名称 %% %号本身
str转换为datetime
import datetime str_p = '2019-01-30 15:29:08' dateTime_p = datetime.datetime.strptime(str_p,'%Y-%m-%d %H:%M:%S') print(dateTime_p) # 2019-01-30 15:29:08
str转换为date
#!/usr/bin/env python3 import datetime str_p = '2019-01-30' date_p = datetime.datetime.strptime(str_p,'%Y-%m-%d').date() print(date_p,type(date_p)) # 2019-01-30 <class 'datetime.date'>
天数加减
#!/usr/bin/env python3 import datetime # today = datetime.datetime.today() today = datetime.datetime.today().date() yestoday = today + datetime.timedelta(days=-1) tomorrow = today + datetime.timedelta(days=1) print(today) # 2019-01-30 print(yestoday)# 2019-01-29 print(tomorrow)# 2019-01-31
strftime()和strptime()函数的描述与用法
-
strftime()函数用来表示时间元组,返回可读字符串表示的当前时间,由()里面的参数决定格式。
-
strptime()函数是按照特定时间格式将字符串转换成时间类型。它们重点是格式之间的转换。
-
datetime.now():获取电脑当前时间,且随着电脑配置时间而改变,不带时区。(例如中国北京时间)
-
datetime.utcnow():获取世界标准时区的当前时间,与电脑配置无关,带时区。(例如格林威治时间)
from datetime import datetime #调用datetime模块,以便使用strftime和strptime函数 # 输出'2021-11-01 09:46:33' datetime.now().strftime('%Y-%m-%d %H:%M:%S') #获取当前时间,并按照年月日,时分秒格式输出 # 输出'datetime.datetime(2021, 11, 1, 9, 30, 30)' datetime.strptime('2021-11-01 09:30:30','%Y-%m-%d %H:%M:%S') #将上述的时间格式转换为字符串格式
13 修改PIP源
1 import os,sys,platform 2 ini="""[global] 3 index-url = https://pypi.doubanio.com/simple/ 4 [install] 5 trusted-host=pypi.doubanio.com 6 """ 7 os_version=platform.platform() 8 if 'Windows' in os_version: 9 os_flag=False 10 file_name='pip.ini' 11 else: 12 os_flag=True 13 file_name='pip.conf' 14 if os_flag==True: 15 pippath=os.environ["HOME"]+os.sep+".pip"+os.sep 16 else: 17 pippath=os.environ["USERPROFILE"]+os.sep+"pip"+os.sep 18 if not os.path.exists(pippath): 19 os.mkdir(pippath) 20 with open(pippath+file_name,"w") as f: 21 f.write(ini)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix