2

I used gspread and pandas to convert my google sheet into a list of dictionaries. My google sheet is shown as the following list: (It's a very long list, so I only list a few lines)

mysheet=[{'StartDate': '2021-10-02', 'ID': 11773, 'Receiver': Mike},{'StartDate': '2021-11-02', 'ID': 15673, 'Receiver': Jane}, ... {'StartDate': '2021-10-10', 'ID': 34653, 'Receiver': Jack}]

I want to add a key/value pair to this list, and the value will use the values from the former cells with a function. For example, I want to calculate how many days from today,so my list will show as this:

mysheetnew=[{'StartDate': '2021-10-02', 'ID': 11773, 'Receiver': Mike, 'Days':66 },{'StartDate': '2021-10-03', 'ID': 15673, 'Receiver': Jane, 'Days':65}, ... {'StartDate': '2021-10-5', 'ID': 34653, 'Receiver': Jack, 'Days':63}]

Please help :)

NixonSparrow
  • 6,130
  • 1
  • 6
  • 18
Mary
  • 231
  • 1
  • 3
  • 12
  • 1
    Does this answer your question? [How to calculate number of days between two given dates](https://stackoverflow.com/questions/151199/how-to-calculate-number-of-days-between-two-given-dates) I'm assuming the other date in this case is "now" – C.Nivs Feb 03 '22 at 14:26
  • Thank you so much!! The function is useful and I think I will use that, but I don't know how to add that function to my list. I'm new to python. Could you please advise on this – Mary Feb 03 '22 at 14:35

1 Answers1

2

You can use

mysheetnew = []
for item in mysheet:
    temp = item.copy()
    temp["keyname"] = value
    mysheetnew.append(temp)

and instead of values, you can put func(temp["date"]) or else. Hope it helped.

Edit : More precisely

import datetime

mysheetnew = []
for item in mysheet:
    temp = item.copy()
    timediff = datetime.datetime.now() - datetime.datetime.strptime(temp["StartDate"], "%Y-%m-%d")
    temp["Days"] = timediff.days
    mysheetnew.append(temp)

This makes use of the datetime module to manipulate dates and to have the difference between two dates.

Nifle CGE
  • 38
  • 8
  • 1
    Thank you so much for your answer! I successfully added a new pair with your code! Could you please explain more about that function part with my example? I don't know how to define and add that function in. – Mary Feb 03 '22 at 14:48
  • 1
    @mary-ma i have edited the post with the more advanced answer – Nifle CGE Feb 03 '22 at 15:33