Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The task is pretty simple and i'm able to partially accomplish it:

from dateutil.parser import parse

    for timestamp, grp in itertools.groupby(transactions, lambda x: parse(x['date']).hour):
        group = list(grp)
        logger.info(f'{timestamp} : {len(group)}')

-> i get the hour:count array.

However i want to have a datetime:count array as a result (where datetime object represent one hour).

Does i have to build the datetime object in lambda x function? (i.e. get x['date']).hour, x['date']).day, x['date']).month etc. and create a new datetime using those values) or there is another way?

sample input(transactions) contains data for weeks/months:

[
 {
  'date': '2018-12-04T15:34:40+00:00',
  'data': 'blabla'
 },
 {
  'date': '2018-12-04T15:38:40+00:00',
  'data': 'blabla'
 },
 {
  'date': '2018-12-04T15:45:40+00:00',
  'data': 'blabla'
 },
]

sample output:

2018-12-04 13:00:00+00:00 : 6
2018-12-04 14:00:00+00:00 : 1
2018-12-04 15:00:00+00:00 : 2

Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
326 views
Welcome To Ask or Share your Answers For Others

1 Answer

You need to use a datetime object as key, I used now as the date but you can use the original date:

import itertools
import datetime
from dateutil.parser import parse

transactions = ['2018-12-04 13:{}0:00+00:00'.format(i) for i in range(6)] + 
               ['2018-12-04 14:{}0:00+00:00'.format(i) for i in range(1)] + 
               ['2018-12-04 15:{}0:00+00:00'.format(i) for i in range(2)]
for timestamp, grp in itertools.groupby(transactions, key=lambda x: datetime.datetime.combine(parse(x).date(), datetime.time(parse(x).hour, 0, 0, 0))):
    count = list(grp)
    print('{}:{}'.format(timestamp, len(count)))

Output

2018-12-04 13:00:00:6
2018-12-04 14:00:00:1
2018-12-04 15:00:00:2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...