简体   繁体   中英

Dates from dict to list

This is too complicated for me, so I'm asking for help. I have dict with like this:

dict = {'date_from': u'2019-04-01', 
        'date_to': u'2019-04-30'}

and from this dict, I need to make a list like this:

list = ['2019-04']

since the month is the same.

If dict is like this

dict = {'date_from': u'2019-04-01', 
        'date_to': u'2019-05-30'}

the list should be like:

list = ['2019-04', '2019-05']

and so on.

Another Example

dict = {'date_from': u'2019-01-01', 
         'date_to': u'2019-05-30'}


list = ['2019-01', '2019-02','2019-03','2019-04','2019-05']

I know that this is possible, but can't figure out how to make it work.

Using datetime & relativedelta

Ex:

import datetime
from dateutil.relativedelta import relativedelta

d = {'date_from': u'2019-01-01', 'date_to': u'2019-05-30'}
result = []
start = datetime.datetime.strptime(d["date_from"], "%Y-%m-%d") 
end = datetime.datetime.strptime(d["date_to"], "%Y-%m-%d")
while True:
    if start > end:
        break
    result.append(start.strftime("%Y-%m"))
    start = start + relativedelta(months=1)
print(result)   

Output:

['2019-01', '2019-02', '2019-03', '2019-04', '2019-05']

You can use list comprehension:

import datetime

d1= datetime.datetime(2019, 1, 1, 0, 0)
d2= datetime.datetime(2020, 5, 30, 0, 0)

rslt= [ f"{year}-{month:02}" for year in range(d1.year,d2.year+1) for month in range(1,13) if (d1.year,d1.month)<=(year,month)<=(d2.year,d2.month)]

print(rslt)

Out: ['2019-01', '2019-02', '2019-03', '2019-04', '2019-05', '2019-06', '2019-07', '2019-08', '2019-09', '2019-10', '2019-11', '2019-12', '2020-01', '2020-02', '2020-03', '2020-04', '2020-05']

Edit: We dont need the datetime object.

dd = {'date_from': '2019-04-01', 
        'date_to': '2020-05-30'}

d1year, d1month, d1day= [ int(e) for e in dd['date_from'].split("-") ]
d2year, d2month, d2day= [ int(e) for e in dd['date_to'].split("-") ]

rslt= [ f"{year}-{month:02}" for year in range(d1year,d2year+1) for month in range(1,13) if (d1year,d1month)<=(year,month)<=(d2year,d2month)]

print(rslt)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM