M
M
MonsterAndrew2017-09-30 20:19:21
Python
MonsterAndrew, 2017-09-30 20:19:21

How to sort items by date in Python?

There is an array with elements of type dict.

lst = [{"date": "2017-09-03"}, {"date": "2017-09-02"}, {"date": "2017-09-01"}]

Only the length of the array is about 20. We need to make sure that only elements with today's date and + - 4 days remain. Those. for example, today is the 5th, it is necessary that only 9-1 remain.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MonsterAndrew, 2017-09-30
@MonsterAndrew

def filtr(mass, days_ago, days_future):
    delta1 = timedelta(days=days_ago)
    delta2 = timedelta(days=days_future)
    delta3 = timedelta(days=1)
    new = []
    today = datetime.today()
    for el in mass:
        to_date = datetime.strptime(el['date'], '%Y-%m-%d')
        if to_date >= today and (to_date - today) <= delta2:
            new.append(el)
        elif to_date <= today and (today - to_date) <= delta1+delta3:
            new.append(el)
    return new

V
Vladimir Kuts, 2017-09-30
@fox_12

> It is necessary to make sure that only elements with today's date and + - 4 days remain.
It's a filter then. For example like this:

import datetime
lst = [{'date': '2017-09-03'}, {'date': '2017-09-02'}, {'date': '2017-09-01'}, {'date': '2017-09-28'}, {'date': '2017-10-02'}]

now = datetime.datetime.now()

lst2 = filter(lambda x: datetime.datetime.strptime(x['date'], '%Y-%m-%d')>now-datetime.timedelta(days=4) and datetime.datetime.strptime(x['date'], '%Y-%m-%d')<now+datetime.timedelta(days=4), lst)

>>> lst2
[{'date': '2017-09-28'}, {'date': '2017-10-02'}]

rest of the array
Result:
>>> lst2 + lst_sorted
[{'date': '2017-09-28'}, {'date': '2017-10-02'}, {'date': '2017-09-01'}, {'date': '2017-09-02'}, {'date': '2017-09-03'}]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question