欢迎访问宙启技术站
智能推送

Python中常用的common.utils工具类介绍

发布时间:2023-12-13 09:56:04

common.utils是一个Python中常用的工具类,用于提供一些常用的功能函数,以简化开发过程。下面将介绍一些常用的函数,并提供使用例子。

1. 判断一个字符串是否是整数 is_integer(str)

该函数用于判断一个字符串是否能转换为整数。返回True表示可以转换为整数,返回False表示不能转换为整数。

from common.utils import is_integer

num1 = '123'
num2 = 'abc'

print(is_integer(num1))  # True
print(is_integer(num2))  # False

2. 判断一个字符串是否是浮点数 is_float(str)

该函数用于判断一个字符串是否能转换为浮点数。返回True表示可以转换为浮点数,返回False表示不能转换为浮点数。

from common.utils import is_float

num1 = '123.45'
num2 = 'abc'

print(is_float(num1))  # True
print(is_float(num2))  # False

3. 将字符串转换为整数或浮点数 convert_to_number(str)

该函数用于将一个字符串转换为整数或浮点数。如果字符串可以转换为整数,则返回整数值;如果字符串可以转换为浮点数,则返回浮点数值;如果字符串不能转换为数字,则返回原字符串。

from common.utils import convert_to_number

num1 = '123'
num2 = '123.45'
num3 = 'abc'

print(convert_to_number(num1))  # 123
print(convert_to_number(num2))  # 123.45
print(convert_to_number(num3))  # abc

4. 获取当前时间字符串 get_current_time()

该函数用于获取当前时间的字符串表示。返回的字符串格式为"YYYY-mm-dd HH:MM:SS"。

from common.utils import get_current_time

current_time = get_current_time()
print(current_time)  # 2022-01-01 14:30:45

5. 将时间字符串转换为时间戳 convert_to_timestamp(time_str)

该函数用于将一个时间字符串转换为时间戳。时间字符串的格式必须为"YYYY-mm-dd HH:MM:SS"。返回的时间戳是一个整数值,表示从1970年1月1日 00:00:00 UTC到给定时间的秒数。

from common.utils import convert_to_timestamp

time_str = '2022-01-01 14:30:45'
timestamp = convert_to_timestamp(time_str)
print(timestamp)  # 1641029445

6. 将时间戳转换为时间字符串 convert_to_time_str(timestamp)

该函数用于将一个时间戳转换为时间字符串。返回的时间字符串的格式为"YYYY-mm-dd HH:MM:SS"。

from common.utils import convert_to_time_str

timestamp = 1641029445
time_str = convert_to_time_str(timestamp)
print(time_str)  # 2022-01-01 14:30:45

7. 随机生成一个指定长度的字符串 generate_random_string(length)

该函数用于随机生成一个指定长度的字符串。参数length表示要生成的字符串的长度。返回的字符串由随机的字母和数字组成。

from common.utils import generate_random_string

random_string = generate_random_string(10)
print(random_string)  # a4bF23CfG7

8. 获取一个文件的md5值 get_file_md5(file_path)

该函数用于获取一个文件的md5值。参数file_path表示文件的路径。返回的md5值是一个字符串,表示文件内容的唯一标识。

from common.utils import get_file_md5

file_path = 'test.txt'
md5_value = get_file_md5(file_path)
print(md5_value)  # e1a9cbbdf19b023744a14a329ae80331

这些是common.utils中常用的一些函数,能够在开发过程中提供帮助。使用这些函数可以简化代码,提高开发效率。