tips of python3

本文汇总了Python编程中实用的时间处理、数值运算、字典操作、函数映射、字符串转换等技巧,涵盖从时间差计算到环境配置的多个方面,为Python开发者提供了一站式的代码优化指南。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、计算时间差

import datetime
# 返回当前时间的两分钟前
ten_minutes_before = (datetime.datetime.now() + datetime.timedelta(minutes=-10)).strftime('%Y-%m-%d %H:%M:%S')
print(ten_minutes_before)

# 返回当前时间的两小时前
two_hours_before = (datetime.datetime.now() + datetime.timedelta(hours=-2)).strftime('%Y-%m-%d %H:%M:%S')
print(two_hours_before)

2、四舍五入返回一个精确的小数值

from decimal import Decimal
print(Decimal('3.155').quantize(Decimal("0.01"), rounding = "ROUND_HALF_UP"))
# 3.16

3、字典默认的key的值,常用于 不定key 的值列表 追加元素

from collections import defaultdict

# 将列表内的元素,根据 位数 合并成字典
lst = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 32769, 65536, 4294967296]

dic = defaultdict(list)

for i in lst:
    dic[len(str(i))].append(i)

print(dict(dic))

4、主函数入口选项,可以设置 function - mapping

def login():
    pass


def register():
    pass


def add_to_car():
    pass


def show_goods():
    pass


if __name__ == '__main__':
    func_map = {'1': login, '2': register, '3': add_to_car, '4': show_goods}
    inp = input('请输入功能选项:')
    if inp in func_map:
        func_map[inp]()

4.v2 主函数入口选项 Code Review :getattr hasattr 反射的应用

class FTP(object):

    def __init__(self):
        self.run()

    def run(self):
        print('''
           提示:
               上传:   put 路径/文件名称
               下载:   get 路径/文件名称
        
        '''
        )
        while 1:
            input_str=input(">>>")
            action, params = input_str.split(" ")
            if hasattr(self, action):
                getattr(self, action)()
            else:
                print("不存在该方法")

    def put(self):
        print("上传...")

    def get(self):
        print("下载...")


ftp = FTP()

5、假如接收的文件地址是一个变量

path = "/data/lol/小电影.rmvb"

1、字符串
  r"path_str"
  
2、变量
r 后拼接变量的格式化输出
如: 
d = r'%s' %path
d = rf'{path}'
d = r'{0}'.format(path)

6、将字符串转化为 字节 形式

  • 字符串
In [16]: print(b'str1', type(b'str1'))
b'str1' <class 'bytes'>
  • 字符串是一个变量
In [18]: s1 = 'str1'

In [19]: print(s1, type(s1))
str1 <class 'str'>

In [20]: print(s1.encode('utf-8'), type(s1.encode('utf-8')))
b'str1' <class 'bytes'>
  • 7、pip国内源 加速
pip3 install requests  -i http://mirrors.aliyun.com/pypi/simple/   --trusted-host mirrors.aliyun.com

'''
清华:https://pypi.tuna.tsinghua.edu.cn/simple
阿里云:http://mirrors.aliyun.com/pypi/simple/
中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/
华中理工大学:http://pypi.hustunique.com/
山东理工大学:http://pypi.sdutlinux.org/
豆瓣:http://pypi.douban.com/simple/
'''

pip源加速,永久

mkdir ~/.pip

打开配置文件 ~/.pip/pip.conf,修改如下:

[global]
index-url = http://mirrors.aliyun.com/pypi/simple/ 
[install]
trusted-host = mirrors.aliyun.com
# 查看pip源
 pip3 config list   

win下指定pip源:
Windows下,你需要在当前对用户目录下(C:\Users\xx\pip,xx 表示当前使用对用户,比如张三)创建一个 pip.ini在pip.ini文件中输入以下内容:

[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
[install]
trusted-host = pypi.tuna.tsinghua.edu.cn
  • 8、pycharms 远程调试代码
1、pycharm 连接远程开发机
http://testingpai.com/article/1596527035281

2、pycharm 远程调试开发机代码,自动推送代码到开发机
https://zhuanlan.zhihu.com/p/36843200

3、pycharm 推送代码到git
https://zhuanlan.zhihu.com/p/93852858
  • 9、系统打开show 图像
def show_graph(file_path):
    import os
    import platform
    import subprocess
    user_platform = platform.system()	 # 获取操作系统
    if user_platform == 'Darwin':		 # Mac
        subprocess.call(['open', file_path])
    elif user_platform == 'Linux':	     # Linux
        subprocess.call(['xdg-open', file_path])
    else:								 # Windows
        os.startfile(file_path)

# show_graph('filename.png')
  • 10、获取最大数
    在这里插入图片描述
  • 11、获取时间段
def date_range(begin_date, end_date):
	dates = []
	from datetime import datetime.timedelta
	dt = datetime.strptime(beginDate, "%Y-%m-%d")
	date = begin_date[:]
	while date <= end_date:
	    dates.apped(date)
	    dt = dt+ timedalta(1)
	    date = dt.strftime("%Y-%m-%d")
	return dates

date_list = date_range("2023-10-24", "2024-10-24")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值