1

I've been googling for answers for about 2 days now and I'm still stuck.

I have a huge list of dates and numbers like this:

 1.1.2018 0:00;2590
 3.1.2018 1:00;2530
 4.2.2018 2:00;1700
 6.2.2018 3:00;2340
 18.3.2018 4:00;1800
 15.4.2018 5:00;2850
 ...

And I need to add all numbers together that have the same week number and return total of numbers in a week like this:

0;0
1;549730
2;645010
3;681320
4;677060
5;698450
...etc
52;576280
53;81640

This is my code so far, I've separated the dates and numbers in their own lists but not sure how to go on from here. I'm supposed to use strftime %W somehow, but don't know how.

import datetime
from datetime import date
from datetime import datetime

def main():
    file = open("2018Electricity.txt", "r")
    line = file.readline()
    time_list = []
    electricity_list = []
    total = []

    for i in file:
        time = i.strip().split(';')[0]
        electricity = i.strip().split(';')[1]
        time_list.append(datetime.strptime(time, '%d.%m.%Y %H:%M'))
        electricity_list.append(electricity)
        
    file.close()

main()
Hueqen
  • 35
  • 3
  • 1
    Does this answer your question: [How to get week number in Python?](https://stackoverflow.com/questions/2600775/how-to-get-week-number-in-python) – ItaiS Oct 12 '20 at 06:08
  • What does each element in each line represent – dee cue Oct 12 '20 at 06:08

1 Answers1

1

Just use a simple dictionary and run it sequentially.

import datetime
def solution():
    data = [
        "1.1.2018 0:00;2590",
        "3.1.2018 1:00;2530",
        "4.2.2018 2:00;170",
        "6.2.2018 3:00;2340",
        "18.3.2018 4:00;1800",
        "15.4.2018 5:00;2850"
    ]

    result = {} # store in a dictionary

    for date in data:
        day = int(date.split(".")[0])
        month = int(date.split(".")[1])
        year = int(date.split(".")[2][0:5])
        week = datetime.date(year, month, day).isocalendar()[1]
        if week not in result:
            result[week] = 0
        result[week] += int(date.split(";")[1])
    return result

result = solution()
for week, value in result.items():
    print(f"{week};{value}")
kennysliding
  • 2,783
  • 1
  • 10
  • 31
  • Is there a way to do this with a list instead? And also so it returns 0;0 & and week 53 as well? Because right now it returns weeks 1-52 and week 1 added week 53's numbers to it. – Hueqen Oct 15 '20 at 11:44
  • please have a look at [strptime](https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime) ;-) – FObersteiner Oct 20 '20 at 10:32