Home >  > 一天学会Python Web框架(四)工具函数

一天学会Python Web框架(四)工具函数

0

一、convert_helper.py

在common文件夹下面建立convert_helper.py文件。

convert_helper.py是类型转换包,所有字符串转数值、字符串转日期、字符串日期转时间戳等各种类型转换函数,都可以放到这里来。

1#!/usr/bin/evn python
2# coding=utf-8
3 
4import decimal
5import datetime
6 
7 
8#############################################
9# 数值型转换函数
10#############################################
11def to_int(text):
12    """将字符串安全转换为int类型,转换失败时默认值为0"""
13    try:
14        return int(text)
15    except:
16        return 0
17 
18 
19def to_int0(text):
20    """将字符串安全转换为int类型,当int值小于0时,返回0"""
21    result = to_int(text)
22 
23    # 判断转换后的结果值是否小于0,是的话返回0
24    if not result or result < 0:
25        return 0
26    else:
27        return result
28 
29 
30def to_int1(text):
31    """将字符串安全转换为int类型,当int值小于1时,返回1"""
32    result = to_int(text)
33 
34    # 判断转换后的结果值是否小于1,是的话返回1
35    if not result or result < 1:
36        return 1
37    else:
38        return result
39 
40 
41def to_float(text):
42    """将字符串安全转换为float类型"""
43    try:
44        return float(text)
45    except:
46        return 0.0
47 
48 
49def to_decimal(text):
50    """将字符串安全转换为int类型"""
51    try:
52        return decimal.Decimal(text)
53    except:
54        return 0
55 
56 
57#############################################
58# 日期型转换函数
59#############################################
60def to_datetime(text):
61    """字符串转时间"""
62    if not text:
63        return None
64 
65    # 定义字典根据时间字符串匹配不同的格式
66    time_dict = {
67        1: "%Y-%m-%d %H:%M:%S.%f",
68        2: "%Y-%m-%d %H:%M",
69        3: "%Y-%m-%d %H:%M:%S",
70    }
71    # 如果中间含有时间部分就用:判断
72    try:
73        if str(text).find('.') > -1:
74            return datetime.datetime.strptime(text, time_dict[1])
75        elif ':' in text:
76            time_list = text.split(':')
77            return datetime.datetime.strptime(text, time_dict[len(time_list)])
78        else:
79            return datetime.datetime.strptime(text, "%Y-%m-%d")
80    except:
81        return None
82 
83 
84def to_date(text):
85    """字符串转日期"""
86    d = to_datetime(text)
87    if d:
88        return d.date()
89 
90 
91def to_timestamp10(text):
92    """将时间格式的字符串转化为长度为10位长度的时间戳"""
93    d = to_datetime(text)
94    if d:
95        return int(d.timestamp())
96    else:
97        return 0
98 
99 
100def to_timestamp13(text):
101    """将时间格式的字符串转化为长度为13位长度的时间戳"""
102    d = to_datetime(text)
103    if d:
104        return int(d.timestamp() * 1000)
105    else:
106        return 0

比如说字符转int函数

1def to_int(text):
2    """将字符串安全转换为int类型,转换失败时默认值为0"""
3    try:
4        return int(text)
5    except:
6        return 0

在日常使用当中,经常会要求数值不能小于0或小于1,而to_int()函数转换时,用户如果输入了负数,虽然转换成功了,但这个值却不是我们想要的结果,如果每次都要加上一段代码对值进行判断,那会更加麻烦,所以进行了再次封装,多出来to_int0()和to_int()1两个函数。

1def to_int0(text):
2    """将字符串安全转换为int类型,当int值小于0时,返回0"""
3    result = to_int(text)
4 
5    # 判断转换后的结果值是否小于0,是的话返回0
6    if not result or result < 0:
7        return 0
8    else:
9        return result
10 
11 
12def to_int1(text):
13    """将字符串安全转换为int类型,当int值小于1时,返回1"""
14    result = to_int(text)
15 
16    # 判断转换后的结果值是否小于1,是的话返回1
17    if not result or result < 1:
18        return 1
19    else:
20        return result

 to_datetime()函数,会根据输入的日期字符串格式,转换成对应的日期(如:2017-09-01)、日期时间(2017-09-01 11:11)、日期时分秒(2017-09-01 11:11:11)、日期时分秒毫秒类型(2017-09-01 11:11:11.111),得到的值是datetime类型

1def test_to_datetime(self):
2        print('---test_to_datetime---')
3        print(convert_helper.to_datetime(None))
4        print(convert_helper.to_datetime(''))
5        print(convert_helper.to_datetime('xxx'))
6        print(convert_helper.to_datetime('2017-09-01'))
7        print(convert_helper.to_datetime('2017-09-01 11:11'))
8        print(convert_helper.to_datetime('2017-09-0111:11'))
9        print(convert_helper.to_datetime('2017-09-01 11:11:11'))
10        print(convert_helper.to_datetime('2017-09-01 11:11:11.111'))

二、datetime_helper.py
这个日期函数操作包,这个包里的函数类型主要有两大类,一种是日期类型转换,将日期类型格式化为字符串类型或转换为数值类型;另一种是对日期类型的比较或运算。

1#!/usr/bin/evn python
2# coding=utf-8
3 
4import time
5import datetime
6 
7 
8def to_date(dt):
9    """将时间格式化为日期字符串"""
10    if isinstance(dt, datetime.datetime):
11        return dt.strftime('%Y-%m-%d')
12    elif isinstance(dt, datetime.date):
13        return dt.strftime('%Y-%m-%d')
14    else:
15        raise Exception("日期类型错误")
16 
17 
18def to_datetime(dt):
19    """将时间格式化为日期时间字符串"""
20    if isinstance(dt, datetime.datetime):
21        return dt.strftime('%Y-%m-%d %H:%M:%S')
22    elif isinstance(dt, datetime.date):
23        return dt.strftime('%Y-%m-%d')
24    else:
25        raise Exception("日期类型错误")
26 
27 
28def to_number():
29    """当前时间转换为年月日时分秒毫秒共10位数的字符串"""
30    return datetime.datetime.now().strftime('%Y%m%d%H%M%S')
31 
32 
33def to_timestamp10():
34    """获取当前时间长度为10位长度的时间戳"""
35    return int(time.time())
36 
37 
38def to_timestamp13():
39    """获取当前时间长度为13位长度的时间戳"""
40    return int(time.time() * 1000)
41 
42 
43def timedelta(sign, dt, value):
44    """
45    对指定时间进行加减运算,几秒、几分、几小时、几日、几周、几月、几年
46    sign: y = 年, m = 月, w = 周, d = 日, h = 时, n = 分钟, s = 秒
47    dt: 日期,只能是datetime或datetime.date类型
48    value: 加减的数值
49    return: 返回运算后的datetime类型值
50    """
51    if not isinstance(dt, datetime.datetime) and not isinstance(dt, datetime.date):
52        raise Exception("日期类型错误")
53 
54    if sign == 'y':
55        year = dt.year + value
56        if isinstance(dt, datetime.date):
57            return datetime.datetime(year, dt.month, dt.day)
58        elif isinstance(dt, datetime.datetime):
59            return datetime.datetime(year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond)
60        else:
61            return None
62    elif sign == 'm':
63        year = dt.year
64        month = dt.month + value
65        ### 如果月份加减后超出范围,则需要计算一下,对年份进行处理 ###
66        # 如果月份加减后等于0时,需要特殊处理一下
67        if month == 0:
68            year = year - 1
69            month = 12
70        else:
71            # 对年月进行处理
72            year = year + month // 12
73            month = month % 12
74        if isinstance(dt, datetime.date):
75            return datetime.datetime(year, month, dt.day)
76        elif isinstance(dt, datetime.datetime):
77            return datetime.datetime(year, month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond)
78        else:
79            return None
80    elif sign == 'w':
81        delta = datetime.timedelta(weeks=value)
82    elif sign == 'd':
83        delta = datetime.timedelta(days=value)
84    elif sign == 'h':
85        delta = datetime.timedelta(hours=value)
86    elif sign == 'n':
87        delta = datetime.timedelta(minutes=value)
88    elif sign == 's':
89        delta = datetime.timedelta(seconds=value)
90    else:
91        return None
92 
93    return dt + delta

to开头的函数都是时间类型转换函数(PS:convert_helper.py包里是对日期格式字符串转为时间类型,而datetime_helper.py里所有操作,都是对时间类型进行处理的,将它们转为其他格式)

暧昧帖

本文暂无标签

发表评论

*

*