sum up purchases of current year and month

Question:

I need to add the purchases of users in a list with the following conditions:

"Those customers who have a sum of purchases in the current year of 15,000 or more are entitled to a 20% discount. If they have also spent 3000 or more in the current month, they have an additional 15%."

The list is the following:

purchases=[{"id": "123", 'price':16000, 'date': "(2022, 3, 12)"},{"id": "123", 'price':4000, 'date': "(2022, 11, 20)"}]

I don’t know how to add up the purchases in the current year and month, if someone can help 🙂

Asked By: Pani Hardoy

||

Answers:

You can get the current year and month from datetime.date.today() (See Datetime current year and month in Python)

import datetime

today = datetime.date.today()

# Current year: today.year
# Current month today.month

Iterate over each element of purchases. The "date" key in each element tells you the date for that purchase. It’s annoying that the value at this key is a string representation of a tuple, but we can parse it using ast.literal_eval.

The first element of this tuple is the year for the purchase. The second element is the month. So we need to check if these values match the values for today, and add to the corresponding totals:

import ast

total_month = 0
total_year = 0

for purchase in purchases:
    p_date = ast.literal_eval(purchase["date"])
    if p_date[0] == today.year:
        total_year += purchase["price"]
    if p_date[1] == today.month:
        total_month += purchase["price"]

And after we’ve looked through all purchases, we can check our criteria:

if total_year >= 15_000:
    print("20% discount")
    if total_month >= 3000:
        print("Extra 15% discount")
Answered By: Pranav Hosangadi
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.