xingxingnbsp

1. 时间

1.1 python-时间戳处理

import time

# 1. python 获取当前时间戳
def get_now_time_stamp():
    print("打印当前时间戳: ", time.time())


# 2. python 时间戳 → 时间元祖
def time_stamp_to_time_tuple():
    """
    什么是时间元组?
    很多Python函数用一个元组装起来的9组数字处理时间:
    序号    字段            值
    0        4位数年            2008
    1        月                1 到 12
    2        日                1到31
    3        小时            0到23
    4        分钟            0到59
    5        秒                0到61 (60或61 是闰秒)
    6        一周的第几日        0到6 (0是周一)
    7        一年的第几日        1到366 (儒略历)
    8        夏令时            -1, 0, 1, -1是决定是否为夏令时的旗帜

    上述也就是struct_time元组。这种结构具有如下属性:
    序号    属性        值
    0        tm_year        2008
    1        tm_mon        1 到 12
    2        tm_mday        1 到 31
    3        tm_hour        0 到 23
    4        tm_min        0 到 59
    5        tm_sec        0 到 61 (60或61 是闰秒)
    6        tm_wday        0到6 (0是周一)
    7        tm_yday        一年中的第几天,1 到 366
    8        tm_isdst    是否为夏令时,值有:1(夏令时)、0(不是夏令时)、-1(未知),默认 -1
    """
    appoint_time_stamp = 1596435291.554837
    # 默认当前时间
    print("打印当前时间戳转时间元祖: ", time.localtime())
    print("打印当前时间戳转时间元祖: ", time.localtime(time.time()))
    # 指定时间戳
    print("打印指定时间戳转时间元祖: ", time.localtime(appoint_time_stamp))


# 3. python 时间戳 → 可视化时间
def time_stamp_to_visualization_time():
    appoint_time_stamp = 1596435291.554837
    # 默认当前时间戳
    print("打印当前时间戳转可视化时间: ", time.ctime())
    print("打印当前时间戳转可视化时间: ", time.ctime(time.time()))
    # 指定时间戳
    print("打印指定时间戳转可视化时间: ", time.ctime(appoint_time_stamp))


# 4. python 时间元祖 → 时间戳
def time_tuple_to_time_stamp(time_tuple):
    print("打印指定时间元祖转时间戳: ", time.mktime(time_tuple))


# 5. python 时间元组 → 可视化时间
def time_tuple_to_visualization_time(time_tuple):
    print("打印指定时间元祖转可视化时间: ", time.asctime(time_tuple))
    print("打印指定时间元祖转可视化时间: ", time.strftime("%Y-%m-%d %H:%M:%S", time_tuple))


# 6. python 可视化时间(定制) → 时间元祖
def visualization_time_to_time_tuple(visualization_time):
    print("打印可视化时间转时间元祖:", time.strptime(visualization_time, \'%Y-%m-%d %H:%M:%S\'))


# 7. 将格式字符串转换为时间戳
def time_str_to_time_stamp(time_str):
    print("将格式字符串转换为时间戳:", time.mktime(time.strptime(time_str, "%a %b %d %H:%M:%S %Y")))


if __name__ == \'__main__\':
    # 打印当前时间戳
    get_now_time_stamp()

    # 打印时间元祖
    time_stamp_to_time_tuple()

    # 打印可视化时间
    time_stamp_to_visualization_time()

    # 时间元祖转时间戳
    time_tuple = (2020, 8, 3, 14, 41, 31, 6, 273, 0)
    time_tuple_to_time_stamp(time_tuple)

    # python 时间元组 → 可视化时间
    time_tuple_to_visualization_time(time_tuple)

    # python 可视化时间(定制) → 时间元祖
    visualization_time = "2020-08-03 14:41:31"
    visualization_time_to_time_tuple(visualization_time)

    # 将格式字符串转换为时间戳
    time_str = "Mon Aug  3 15:06:27 2020"
    time_str_to_time_stamp(time_str)

 

运行结果:

打印当前时间戳:  1598063513.8829813
打印当前时间戳转时间元祖:  time.struct_time(tm_year=2020, tm_mon=8, tm_mday=22, tm_hour=10, tm_min=31, tm_sec=53, tm_wday=5, tm_yday=235, tm_isdst=0)
打印当前时间戳转时间元祖:  time.struct_time(tm_year=2020, tm_mon=8, tm_mday=22, tm_hour=10, tm_min=31, tm_sec=53, tm_wday=5, tm_yday=235, tm_isdst=0)
打印指定时间戳转时间元祖:  time.struct_time(tm_year=2020, tm_mon=8, tm_mday=3, tm_hour=14, tm_min=14, tm_sec=51, tm_wday=0, tm_yday=216, tm_isdst=0)
打印当前时间戳转可视化时间:  Sat Aug 22 10:31:53 2020
打印当前时间戳转可视化时间:  Sat Aug 22 10:31:53 2020
打印指定时间戳转可视化时间:  Mon Aug  3 14:14:51 2020
打印指定时间元祖转时间戳:  1596436891.0
打印指定时间元祖转可视化时间:  Sun Aug  3 14:41:31 2020
打印指定时间元祖转可视化时间:  2020-08-03 14:41:31
打印可视化时间转时间元祖: time.struct_time(tm_year=2020, tm_mon=8, tm_mday=3, tm_hour=14, tm_min=41, tm_sec=31, tm_wday=0, tm_yday=216, tm_isdst=-1)
将格式字符串转换为时间戳: 1596438387.0

 

1.2 python-字符串与时间之间的转换

# python 字符串转时间 - strptime
from datetime import datetime

"""
语法:
    时间.strftime(时间格式)
    datetime.strptime(字符串,时间格式)
  
示范:
    datetime.strptime(str,\'%Y-%m-%d\')
    datetime.now().strftime("%Y-%m-%d %H:%M:%S")
"""

# 字符串转时间
def str_to_datetime(datetime_str, datetime_format):
    S = datetime.strptime(datetime_str, datetime_format)
    print(S, type(S))

# 时间转字符串
def datetime_to_str():
    dt = datetime.now()
    S = dt.strftime(\'%m/%d/%Y %H:%M:%S %p\')
    print(S, type(S))
    S = dt.strftime(\'%A,%B %d,%Y\')
    print(S, type(S))
    s = dt.strftime(\'%B %d,%Y\')
    print(s, type(s))
    txt = (\'%s年%s月%s日星期%s %s时%s分%s秒\' % (dt.strftime(\'%Y\'), dt.strftime(\'%m\'), dt.strftime(\'%d\'), dt.strftime(\'%w\'),dt.strftime(\'%H\'), dt.strftime(\'%M\'), dt.strftime(\'%S\')))
    print(txt)

if __name__ == \'__main__\':
    str_to_datetime(\'2020/08/03\', \'%Y/%m/%d\')
    str_to_datetime(\'2020年8月3日星期一\', \'%Y年%m月%d日星期一\')
    str_to_datetime(\'2019年7月7日星期日8时42分24秒\', \'%Y年%m月%d日星期日%H时%M分%S秒\')
    str_to_datetime(\'7/7/2019\', \'%m/%d/%Y\')
    str_to_datetime(\'2019-07-07\', \'%Y-%m-%d\')
    str_to_datetime(\'7/7/2019 8:42:50\', \'%m/%d/%Y %H:%M:%S\')
    datetime_to_str()

 运行结果:

2020-08-03 00:00:00 <class \'datetime.datetime\'>
2020-08-03 00:00:00 <class \'datetime.datetime\'>
2019-07-07 08:42:24 <class \'datetime.datetime\'>
2019-07-07 00:00:00 <class \'datetime.datetime\'>
2019-07-07 00:00:00 <class \'datetime.datetime\'>
2019-07-07 08:42:50 <class \'datetime.datetime\'>
08/22/2020 10:33:51 AM <class \'str\'>
Saturday,August 22,2020 <class \'str\'>
August 22,2020 <class \'str\'>
2020年08月22日星期6 10时33分51秒

 

1.3 python-日期之天操作

import time
from datetime import datetime, timedelta, date


# 获取今日的开始时间和结束时间
def get_today_start_end():
    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_hour_list():
    time_list = []
    hour_list = [\'{num:02d}\'.format(num=i) for i in range(24)]
    for hour in hour_list:
        start_time = hour + ":00:00"
        end_time = hour + ":59:59"
        time_data = {
            "start_time": start_time,
            "end_time": end_time,
            "hour": hour,
        }
        time_list.append(time_data)
    return time_list


# 获取今天前days天到今天的日期列表
def get_before_day_list(days):
    begin_date = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
    before_day_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")
        before_day_list.append(date_str)
        begin_date += timedelta(days=1)
    return before_day_list


# 获取今天到,今天后days天的日期列表
def get_after_day_list(days):
    begin_date = (datetime.now() + timedelta(days=days)).strftime("%Y-%m-%d")
    fter_day_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")
        fter_day_list.append(date_str)
        begin_date -= timedelta(days=1)
    fter_day_list.reverse()
    return fter_day_list


# 获取当前日期之前的指定天
def get_before_day(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


# 获取当前日期之后的指定天
def get_after_day(days):
    after = (datetime.now() + timedelta(days=days)).strftime("%Y-%m-%d 00:00:00")
    after_date = datetime.strptime(after, "%Y-%m-%d %H:%M:%S")
    return after_date


# 获取两个指定日期之间的日期列表
def get_day_list(start_day, end_day):
    day_list = []
    if isinstance(all([start_day, start_day]), datetime):
        start_date = start_day
        end_date = start_day
    else:
        start_date = datetime.strptime(start_day, "%Y-%m-%d")
        end_date = datetime.strptime(end_day, "%Y-%m-%d")
    while start_date <= end_date:
        date_str = start_date.strftime("%Y-%m-%d")
        day_list.append(date_str)
        start_date += timedelta(days=1)
    return day_list


if __name__ == \'__main__\':
    # 获取今日的开始时间和结束时间
    print("今天开始时间和结束时间: ", get_today_start_end())

    # 获取一天24小时
    print("今天24小时时间列表: ", get_hour_list())

    # 获取今天前5天包括今天的日期列表
    print("今天前5天包括今天的日期列表: ", get_before_day_list(5))

    # 获取今天后5天包括今天的日期列表
    print("今天后5天包括今天的日期列表: ", get_after_day_list(5))

    # 获取当前日期之前的指定天
    print("当前日期之前的指定天: ", get_before_day(5))

    # 获取当前日期之后的指定天
    print("当前日期之后的指定天: ", get_after_day(5))

    # 获取两个指定日期的日期列表
    print("两个指定日期的日期列表: ", get_day_list(\'2020-07-01\', \'2020-07-31\'))

运行结果:

今天开始时间和结束时间:  (\'2020-08-22 00:00:00\', \'2020-08-22 23:59:59\')
今天24小时时间列表:  [{\'hour\': \'00\', \'start_time\': \'00:00:00\', \'end_time\': \'00:59:59\'}, {\'hour\': \'01\', \'start_time\': \'01:00:00\', \'end_time\': \'01:59:59\'}, {\'hour\': \'02\', \'start_time\': \'02:00:00\', \'end_time\': \'02:59:59\'}, {\'hour\': \'03\', \'start_time\': \'03:00:00\', \'end_time\': \'03:59:59\'}, {\'hour\': \'04\', \'start_time\': \'04:00:00\', \'end_time\': \'04:59:59\'}, {\'hour\': \'05\', \'start_time\': \'05:00:00\', \'end_time\': \'05:59:59\'}, {\'hour\': \'06\', \'start_time\': \'06:00:00\', \'end_time\': \'06:59:59\'}, {\'hour\': \'07\', \'start_time\': \'07:00:00\', \'end_time\': \'07:59:59\'}, {\'hour\': \'08\', \'start_time\': \'08:00:00\', \'end_time\': \'08:59:59\'}, {\'hour\': \'09\', \'start_time\': \'09:00:00\', \'end_time\': \'09:59:59\'}, {\'hour\': \'10\', \'start_time\': \'10:00:00\', \'end_time\': \'10:59:59\'}, {\'hour\': \'11\', \'start_time\': \'11:00:00\', \'end_time\': \'11:59:59\'}, {\'hour\': \'12\', \'start_time\': \'12:00:00\', \'end_time\': \'12:59:59\'}, {\'hour\': \'13\', \'start_time\': \'13:00:00\', \'end_time\': \'13:59:59\'}, {\'hour\': \'14\', \'start_time\': \'14:00:00\', \'end_time\': \'14:59:59\'}, {\'hour\': \'15\', \'start_time\': \'15:00:00\', \'end_time\': \'15:59:59\'}, {\'hour\': \'16\', \'start_time\': \'16:00:00\', \'end_time\': \'16:59:59\'}, {\'hour\': \'17\', \'start_time\': \'17:00:00\', \'end_time\': \'17:59:59\'}, {\'hour\': \'18\', \'start_time\': \'18:00:00\', \'end_time\': \'18:59:59\'}, {\'hour\': \'19\', \'start_time\': \'19:00:00\', \'end_time\': \'19:59:59\'}, {\'hour\': \'20\', \'start_time\': \'20:00:00\', \'end_time\': \'20:59:59\'}, {\'hour\': \'21\', \'start_time\': \'21:00:00\', \'end_time\': \'21:59:59\'}, {\'hour\': \'22\', \'start_time\': \'22:00:00\', \'end_time\': \'22:59:59\'}, {\'hour\': \'23\', \'start_time\': \'23:00:00\', \'end_time\': \'23:59:59\'}]
今天前5天包括今天的日期列表:  [\'2020-08-17\', \'2020-08-18\', \'2020-08-19\', \'2020-08-20\', \'2020-08-21\', \'2020-08-22\']
今天后5天包括今天的日期列表:  [\'2020-08-22\', \'2020-08-23\', \'2020-08-24\', \'2020-08-25\', \'2020-08-26\', \'2020-08-27\']
当前日期之前的指定天:  2020-08-17 00:00:00
当前日期之后的指定天:  2020-08-27 00:00:00
两个指定日期的日期列表:  [\'2020-07-01\', \'2020-07-02\', \'2020-07-03\', \'2020-07-04\', \'2020-07-05\', \'2020-07-06\', \'2020-07-07\', \'2020-07-08\', \'2020-07-09\', \'2020-07-10\', \'2020-07-11\', \'2020-07-12\', \'2020-07-13\', \'2020-07-14\', \'2020-07-15\', \'2020-07-16\', \'2020-07-17\', \'2020-07-18\', \'2020-07-19\', \'2020-07-20\', \'2020-07-21\', \'2020-07-22\', \'2020-07-23\', \'2020-07-24\', \'2020-07-25\', \'2020-07-26\', \'2020-07-27\', \'2020-07-28\', \'2020-07-29\', \'2020-07-30\', \'2020-07-31\']

 

1.4 python-日期之周操作

import time
from datetime import datetime, timedelta, date
import datetime as dt


# 获取指定日期是周几
def get_appoint_date_week(day):
    week_day_dict = {
        0: \'星期一\',
        1: \'星期二\',
        2: \'星期三\',
        3: \'星期四\',
        4: \'星期五\',
        5: \'星期六\',
        6: \'星期天\',
    }
    day = datetime.fromtimestamp(time.mktime(time.strptime(day, "%Y-%m-%d"))).weekday()
    return week_day_dict[day]


# 获取周起止时间
def get_week_start_end(year=None, week=None):
    # 如果用户输入年和周
    if year and week:
        start = date(year, 1, 1)
        start += timedelta(7 - start.weekday())
        days = timedelta(weeks=week - 2)
        end = start + days
        return str(end), str(end + timedelta(6))

    # 如果用户只输入周
    elif week:
        year = int(date.today().year)
        if int(week) >= 53:
            Monday = "Error,Week Num greater than 53!"
        else:
            yearstart_str = str(year) + \'0101\'
            yearstart = datetime.strptime(yearstart_str, \'%Y%m%d\')
            yearstartcalendarmsg = yearstart.isocalendar()
            yearstartweekday = yearstartcalendarmsg[2]
            yearstartyear = yearstartcalendarmsg[0]
            if yearstartyear < year:
                daydelat = (8 - int(yearstartweekday)) + (week - 1) * 7
            else:
                daydelat = (8 - int(yearstartweekday)) + (week - 2) * 7
            Monday = (yearstart + timedelta(days=daydelat)).date()
        start_date = datetime.strptime(str(Monday), \'%Y-%m-%d\')
        before = (start_date + timedelta(days=6)).strftime("%Y-%m-%d")
        before_date = str(datetime.strptime(before, "%Y-%m-%d")).replace(" 00:00:00", \'\')
        return str(start_date).replace(" 00:00:00", \'\'), before_date

    # 如果用户未输入
    else:
        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_list(year=None, week=None):
    week_day_list = []
    # 如果用户输入年和周
    if year and week:
        start = dt.date(year, 1, 1)
        start += timedelta(7 - start.weekday())
        days = timedelta(weeks=week - 2)
        end = start + days
        for i in range(7):
            week_date = str(end + timedelta(i))
            week_day_list.append(week_date)

    # 如果用户只输入周
    elif week:
        current = datetime.now()
        start = dt.date(current.year, 1, 1)
        start += timedelta(7 - start.weekday())
        days = timedelta(weeks=week - 2)
        end = start + days
        for i in range(7):
            week_date = str(end + timedelta(i))
            week_day_list.append(week_date)

    # 如果用户未输入
    else:
        # 获取当前时间
        now = datetime.now()
        # 判断今天周几
        day_Week = datetime.now().weekday()
        for i in range(7):
            date = now + timedelta(days=i - day_Week)
            format_date = date.strftime("%Y-%m-%d")
            week_day_list.append(format_date)

    return week_day_list


if __name__ == \'__main__\':
    # 获取指定日期是周几
    print(get_appoint_date_week(\'2020-08-03\'))

    print(get_week_start_end(year=2020, week=32))
    print(get_week_start_end(week=32))
    print(get_week_start_end())

    print(get_week_list(year=2020, week=32))
    print(get_week_list(week=32))
    print(get_week_list())

运行结果:

星期一
(\'2020-08-03\', \'2020-08-09\')
(\'2020-08-03\', \'2020-08-09\')
(\'2020-08-17\', \'2020-08-23\')
[\'2020-08-03\', \'2020-08-04\', \'2020-08-05\', \'2020-08-06\', \'2020-08-07\', \'2020-08-08\', \'2020-08-09\']
[\'2020-08-03\', \'2020-08-04\', \'2020-08-05\', \'2020-08-06\', \'2020-08-07\', \'2020-08-08\', \'2020-08-09\']
[\'2020-08-17\', \'2020-08-18\', \'2020-08-19\', \'2020-08-20\', \'2020-08-21\', \'2020-08-22\', \'2020-08-23\']

 

1.5 python-日期之月操作

from datetime import datetime, timedelta, date
import calendar
import time


# 获取月开始时间和结束时间
def get_month_start_end(year=None, month=None):
    if year and month:
        year = int(year)
        month = int(month)
    elif month:
        year = date.today().year
        month = int(month)
    else:
        year = date.today().year
        month = date.today().month

    firstDayWeekDay, monthRange = calendar.monthrange(year, month)
    start = date(year=year, month=month, day=1)
    end = date(year=year, month=month, day=monthRange)
    return str(start), str(end)


# 获取月的日期列表
def get_month_day_list(year=None, month=None):
    if year and month:
        year = int(year)
        month = int(month)
        if month == 12:
            ndays = (date(year, month, 1) - date(year, month - 1, 1)).days
        else:
            ndays = (date(year, month + 1, 1) - date(year, month, 1)).days

    elif month:
        year = datetime.now().year
        month = int(month)
        ndays = (date(year, month + 1, 1) - date(year, month, 1)).days

    else:
        year = datetime.now().year
        month = datetime.now().month
        ndays = (date(year, month + 1, 1) - date(year, month, 1)).days

    d1 = date(year, month, 1)
    d2 = date(year, month, ndays)
    delta = d2 - d1
    return [(d1 + timedelta(days=i)).strftime(\'%Y-%m-%d\') for i in range(delta.days + 1)]


# 获取年的每个自然月开始时间和结束时间
def get_natural_month_start_end_list(year=None):
    month_start_end_list = []
    if year:
        year = int(year)
    else:
        year = datetime.now().year

    for x in range(1, 13):
        monthRange = calendar.monthrange(year, x)[1]
        startDay = str(year) + "-" + str(x).zfill(2) + "-01"
        endDay = str(year) + "-" + str(x).zfill(2) + "-"
        # 如果不想本月取最后一天取当前日期,可不做判断,直接用endDay = endDay + str(monthRange).zfill(2)
        if x == 12:
            endDay = endDay + str(31).zfill(2)
        else:
            endDay = endDay + str(monthRange).zfill(2)
        month_start_end_list.append([startDay, endDay])
    return month_start_end_list


# 获取本月开始日期到当前日期列表
def get_list_current_month_start_date_to_current_date():
    day_list = []
    now = datetime.now()
    year = now.year
    month = now.month
    day = now.day
    for i in range(1, day + 1):
        str_day = time.strftime("%Y-%m-%d", (year, month, i, 0, 0, 0, 0, 0, 0))
        day_list.append(str_day)
    return day_list


if __name__ == \'__main__\':
    print(get_month_start_end(year=2020, month=8))
    print(get_month_start_end(month=8))
    print(get_month_start_end())

    print(get_month_day_list(year=2020, month=8))
    print(get_month_day_list(month=8))
    print(get_month_day_list())

    print(get_natural_month_start_end_list(year=2020))
    print(get_natural_month_start_end_list())

    print(get_list_current_month_start_date_to_current_date())

运行结果:

(\'2020-08-01\', \'2020-08-31\')
(\'2020-08-01\', \'2020-08-31\')
(\'2020-08-01\', \'2020-08-31\')
[\'2020-08-01\', \'2020-08-02\', \'2020-08-03\', \'2020-08-04\', \'2020-08-05\', \'2020-08-06\', \'2020-08-07\', \'2020-08-08\', \'2020-08-09\', \'2020-08-10\', \'2020-08-11\', \'2020-08-12\', \'2020-08-13\', \'2020-08-14\', \'2020-08-15\', \'2020-08-16\', \'2020-08-17\', \'2020-08-18\', \'2020-08-19\', \'2020-08-20\', \'2020-08-21\', \'2020-08-22\', \'2020-08-23\', \'2020-08-24\', \'2020-08-25\', \'2020-08-26\', \'2020-08-27\', \'2020-08-28\', \'2020-08-29\', \'2020-08-30\', \'2020-08-31\']
[\'2020-08-01\', \'2020-08-02\', \'2020-08-03\', \'2020-08-04\', \'2020-08-05\', \'2020-08-06\', \'2020-08-07\', \'2020-08-08\', \'2020-08-09\', \'2020-08-10\', \'2020-08-11\', \'2020-08-12\', \'2020-08-13\', \'2020-08-14\', \'2020-08-15\', \'2020-08-16\', \'2020-08-17\', \'2020-08-18\', \'2020-08-19\', \'2020-08-20\', \'2020-08-21\', \'2020-08-22\', \'2020-08-23\', \'2020-08-24\', \'2020-08-25\', \'2020-08-26\', \'2020-08-27\', \'2020-08-28\', \'2020-08-29\', \'2020-08-30\', \'2020-08-31\']
[\'2020-08-01\', \'2020-08-02\', \'2020-08-03\', \'2020-08-04\', \'2020-08-05\', \'2020-08-06\', \'2020-08-07\', \'2020-08-08\', \'2020-08-09\', \'2020-08-10\', \'2020-08-11\', \'2020-08-12\', \'2020-08-13\', \'2020-08-14\', \'2020-08-15\', \'2020-08-16\', \'2020-08-17\', \'2020-08-18\', \'2020-08-19\', \'2020-08-20\', \'2020-08-21\', \'2020-08-22\', \'2020-08-23\', \'2020-08-24\', \'2020-08-25\', \'2020-08-26\', \'2020-08-27\', \'2020-08-28\', \'2020-08-29\', \'2020-08-30\', \'2020-08-31\']
[[\'2020-01-01\', \'2020-01-31\'], [\'2020-02-01\', \'2020-02-29\'], [\'2020-03-01\', \'2020-03-31\'], [\'2020-04-01\', \'2020-04-30\'], [\'2020-05-01\', \'2020-05-31\'], [\'2020-06-01\', \'2020-06-30\'], [\'2020-07-01\', \'2020-07-31\'], [\'2020-08-01\', \'2020-08-31\'], [\'2020-09-01\', \'2020-09-30\'], [\'2020-10-01\', \'2020-10-31\'], [\'2020-11-01\', \'2020-11-30\'], [\'2020-12-01\', \'2020-12-31\']]
[[\'2020-01-01\', \'2020-01-31\'], [\'2020-02-01\', \'2020-02-29\'], [\'2020-03-01\', \'2020-03-31\'], [\'2020-04-01\', \'2020-04-30\'], [\'2020-05-01\', \'2020-05-31\'], [\'2020-06-01\', \'2020-06-30\'], [\'2020-07-01\', \'2020-07-31\'], [\'2020-08-01\', \'2020-08-31\'], [\'2020-09-01\', \'2020-09-30\'], [\'2020-10-01\', \'2020-10-31\'], [\'2020-11-01\', \'2020-11-30\'], [\'2020-12-01\', \'2020-12-31\']]
[\'2020-08-01\', \'2020-08-02\', \'2020-08-03\', \'2020-08-04\', \'2020-08-05\', \'2020-08-06\', \'2020-08-07\', \'2020-08-08\', \'2020-08-09\', \'2020-08-10\', \'2020-08-11\', \'2020-08-12\', \'2020-08-13\', \'2020-08-14\', \'2020-08-15\', \'2020-08-16\', \'2020-08-17\', \'2020-08-18\', \'2020-08-19\', \'2020-08-20\', \'2020-08-21\', \'2020-08-22\']

 

1.6 python-日期之年操作

from datetime import datetime
# 获取指定年份的起始日期
def get_yaer_start_end(year=None):
    if year:
        year = year
    else:
        year = datetime.now().year

    start = str(year) + "-01-01"
    end = str(year) + "-12-31"
    return start, end


if __name__ == \'__main__\':
    print(get_yaer_start_end(year=2019))
    print(get_yaer_start_end())

运行结果:

(\'2019-01-01\', \'2019-12-31\')
(\'2020-01-01\', \'2020-12-31\')

 

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(\'416254661@qq.com\'))
    print(url_re(\'http://www.baidu.com\'))

 

 

 

 

 

 

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-06-18
  • 2021-09-03
  • 2022-12-23
  • 2021-12-06
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-11-13
  • 2021-06-20
  • 2021-11-29
  • 2021-08-29
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案