How to iterate through and convert the DateTime in a list of dictionaries to Jalali date format. something like this
list_1 = [{'id': 103, **'date': '2022-07-21'**, 'a_name':'Account Receivable', 'ref': None,
'move_name': 'INV/2022/0012'},{'id': 103, **'date': '2022-07-25'**, 'a_name':'Account
Receivable', 'ref': None,
'move_name': 'INV/2022/0012'},{'id': 103, **'date': '2022-07-28'**, 'a_name':'Account
Receivable', 'ref': None,
'move_name': 'INV/2022/0012'}]
to
list_2 = [{'id': 103, **'date': '1401-05-27'**, 'a_name':'Account Receivable', 'ref': None,
'move_name': 'INV/2022/0012'},{'id': 103, **'date': '1401-05-31'**, 'a_name':'Account
Receivable', 'ref': None,
'move_name': 'INV/2022/0012'},{'id': 103, **'date': '1401-03-02'**, 'a_name':'Account
Receivable', 'ref': None,
'move_name': 'INV/2022/0012'}]
I think, you have an error in the converting of dates. For example, the date 2022-07-21 will not be 1401-05-27, but 1401-04-30 (Correct me, if I'm wrong 🙏🏻)
But if I correctly understood the essence of your problem, then try using the convenient library - persiantools
Installation:
python -m pip install persiantools
Your dictionary is input:
list_1 = [{'id': 103, 'date': '2022-07-21', 'a_name': 'Account Receivable', 'ref': None, 'move_name': 'INV/2022/0012'},
{'id': 103, 'date': '2022-07-25', 'a_name': 'Account Receivable', 'ref': None, 'move_name': 'INV/2022/0012'},
{'id': 103, 'date': '2022-07-28', 'a_name': 'Account Receivable', 'ref': None, 'move_name': 'INV/2022/0012'}]
Program code using the library above:
# Connect the package we need
from persiantools.jdatetime import JalaliDate
import copy
# Create a deep copy of the first list,
# because the list still contains dictionaries
# that also need to be copied
list_2 = copy.deepcopy(list_1)
# Looping through each dictionary and changing its date
for index, elem in enumerate(list_2):
year, month, day = map(int, elem["date"].split("-"))
elem["date"] = JalaliDate.to_jalali(year, month, day).strftime("%Y-%m-%d")
print(list_2)
Output:
list_2 = [{'id': 103, 'date': '1401-04-30', 'a_name': 'Account Receivable', 'ref': None, 'move_name': 'INV/2022/0012'},
{'id': 103, 'date': '1401-05-03', 'a_name': 'Account Receivable', 'ref': None, 'move_name': 'INV/2022/0012'},
{'id': 103, 'date': '1401-05-06', 'a_name': 'Account Receivable', 'ref': None, 'move_name': 'INV/2022/0012'}]