1. 程式人生 > 實用技巧 >python小知識

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])])