sparrow
sparrow

Reputation: 11460

Get the first and last times for each day with Python datetime

I have a list of timestamps in this format: '2016-08-01 13:02:57' or "%Y-%m-%d-%H-%M-%S-%f"

I would like to get the first and last time for each day. So for if there were two days 8/1 and 7/29 the function would return 4 values. For example:

8/1
first: '2016-08-01 13:02:57'
last: '2016-08-01 13:08:44'

7/29
first: '2016-07-29 14:34:02'
last: '2016-07-29 14:37:35'

The first time is the one that occurs first in that day, the last time is the one that occurs last in that day.

Upvotes: 2

Views: 2843

Answers (3)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

Group by year-month-day then get the min and max:

from collections import defaultdict
d = defaultdict(list)
dates = ['2016-08-01 13:02:54',............]
for dte in dates:
    key, _ = dte.split()
    d[key].append(dte)

for k,v in d.items():
    print(min(v), max(v))

Because of the date formats you don't need to convert to datetimes, lexicographical comparison will work fine. You could make a function that does the min and max in one loop but it may not be as fast as the builtins.

Upvotes: 1

Daniel
Daniel

Reputation: 42748

A lexical compare is with your datetime format gives min and max dates. So you simply have to group all datetimes with the same date in one list each:

from collections import defaultdict
dates = ['2016-08-01 13:02:57', '2016-08-01 13:08:44', ...]
dates_and_times = defaultdict(list)
for date in dates:
    d, t = date.split()
    dates_and_times[d].append(t)

for date, times in dates_and_times.items():
    print(date, min(times))
    print(date, max(times))

Upvotes: 1

samlu1999
samlu1999

Reputation: 53

To sensibly group your data I would probably use a dictionary in the following fashion by first splitting your string into the date half and time half.

d = dict()
for item in L:
    if item in d:
        d[item] = [time]
    else:
        d[item].append(time)

Then you have dict mapping certain dates to a list of times. Then it's probably trivial to employ some datetime function which can do max(list) and min(list) to give you earliest and latest times.

Upvotes: -1

Related Questions