Home > Mobile >  sum up purchases of current year and month
sum up purchases of current year and month

Time:11-29

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 :)

CodePudding user response:

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")
  • Related