Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I find the first time of each day in a list of dicts containing timestamps?

I have a list of dicts like this:

data = [
    {"Zeit": datetime(2024, 2, 27, 8, 0), "km": 10},
    {"Zeit": datetime(2024, 2, 27, 13, 30), "km": 20},
    {"Zeit": datetime(2024, 2, 27, 17, 30), "km": 40},
    {"Zeit": datetime(2024, 2, 28, 9, 15), "km": 15},
    {"Zeit": datetime(2024, 2, 28, 14, 45), "km": 25}
]

Now I want to find the first time of each day and assign km = 0. Which should lead to this:

data = [
    {"Zeit": datetime(2024, 2, 27, 8, 0), "km": 0},
    {"Zeit": datetime(2024, 2, 27, 13, 30), "km": 20},
    {"Zeit": datetime(2024, 2, 27, 17, 30), "km": 40},
    {"Zeit": datetime(2024, 2, 28, 9, 15), "km": 0},
    {"Zeit": datetime(2024, 2, 28, 14, 45), "km": 25}
]

How can I do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So far I did not even find a good starting point to approach this issue.

>Solution :

Try:

from datetime import datetime
from itertools import groupby

data = [
    {"Zeit": datetime(2024, 2, 27, 8, 0), "km": 10},
    {"Zeit": datetime(2024, 2, 27, 13, 30), "km": 20},
    {"Zeit": datetime(2024, 2, 27, 17, 30), "km": 40},
    {"Zeit": datetime(2024, 2, 28, 9, 15), "km": 15},
    {"Zeit": datetime(2024, 2, 28, 14, 45), "km": 25},
]

# sort if needed:
# data.sort(key=lambda d: d["Zeit"])

for _, g in groupby(data, lambda d: (d["Zeit"].year, d["Zeit"].month, d["Zeit"].day)):
    first = next(g)
    first["km"] = 0

print(data)

Prints:

[
    {"Zeit": datetime.datetime(2024, 2, 27, 8, 0), "km": 0},
    {"Zeit": datetime.datetime(2024, 2, 27, 13, 30), "km": 20},
    {"Zeit": datetime.datetime(2024, 2, 27, 17, 30), "km": 40},
    {"Zeit": datetime.datetime(2024, 2, 28, 9, 15), "km": 0},
    {"Zeit": datetime.datetime(2024, 2, 28, 14, 45), "km": 25},
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading