python小知识

0820随笔 - python小知识

时间范围

import datetime

# 范围时间
d_time = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '8:00', '%Y-%m-%d%H:%M')
d_time1 = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '12:00', '%Y-%m-%d%H:%M')
print('d_time', d_time, type(d_time))

# 当前时间
n_time = datetime.datetime.now()
print('n_time', n_time, type(n_time))

# 判断当前时间是否在范围时间内
if n_time > d_time and n_time < d_time1:
    print(111)
elif n_time < d_time and n_time > d_time1:
    print(999)
    
# 24小时内
now_time = datetime.datetime.now()    # 当前时间
print(now_time)
print(now_time-datetime.timedelta(hours=24))    # 24小时内

当月数据

import datetime
import calendar
now = datetime.datetime.now()
# 获取当月最后一天的日期
this_month_end = datetime.datetime(now.year, now.month, calendar.monthrange(now.year, now.month)[1]).date()
print('this_month_end', this_month_end)     # 2020-08-31
# 当月所有的日期
date_list = [f"{'-'.join(str(this_month_end).split('-')[0:2])}-{str(i + 1).zfill(2)}" for i in
             range(int(str(this_month_end).split('-')[2]))]
print('date_list', date_list)     # ['2020-08-01', '2020-08-02', ..., '2020-08-30', '2020-08-31']

列表移除元素

import copy
list1 = [{'name': 'aa', 'age': '3'}, {'name': 'bb', 'age': '4'}, {'name': 'cc', 'age': '5'}]
list2 = [{'name': 'cc', 'age': '5'}, {'name': 'bb', 'age': '4'}, {'name': 'aa', 'age': '3'}, {'name': 'aa', 'age': '3'}]

# 方法一   新建一个列表
lt = []
for i in list1:
    if i in list2:
        lt.append(i)
for i in lt:
    list1.remove(i)
    list2.remove(i)
# 方法二   利用深拷贝
list1_copy = copy.deepcopy(list1)
list2_copy = copy.deepcopy(list2)
for i in list1:
    if i in list2:
        list1_copy.remove(i)
        list2_copy.remove(i)
print('list1_copy', list1_copy)
print('list2_copy', list2_copy)


# ###############
a = [a for a in list1 if a in list2]
print('两个列表都存在的元素:', a)

b = [b for b in list1 if b not in list2]
print('在list1不在list2:', b)

c = [c for c in list2 if c not in list1]
print('在list2不在list1:', c)

移除字典中值为空的key

lt = [
    {'flag': 1, 'a': 1, 'b': 2, 'c': ''},
    {'flag': 0, 'a': 'aa', 'b': ' ', 'd': 'cc'}
]
for i in lt:
    dic = {}
    if i.get('flag') == 1:
        dic = {'a': i.get('a'), 'b': i.get('b'), 'c': i.get('c')}
    elif i.get('flag') == 0:
        dic = {'a': i.get('a'), 'b': i.get('b'), 'd': i.get('d')}
    for key in list(dic.keys()):
        if not dic.get(key):
            dic.pop(key)

列表去重顺序保持不变

lists = [2, 3, 1, 3, 4, 4, 2, 1, 1]

out = sorted(list(set(lists)), key=lists.index)
print(out)

获取字典中需要的key

res = [
    {'a': "[]", 'b': "5555555", 'c': 1},
    {'a': "123", 'b': "xxx", 'c': 7},
]
# 需要的字段
append_lt = ['a', 'c']

lt = []
for index, item in enumerate(res):
    dic = {}
    for r in append_lt:
        dic[r] = item.get(r)
    lt.append(dic)
print([dict(t) for t in set([tuple(d.items()) for d in lt])])
posted @ 2020-08-20 10:59  PLPLPL  阅读(128)  评论(0编辑  收藏  举报
// 目录