如何在字典列表中将日期时间格式转换为jalali日期



如何迭代字典列表中的DateTime并将其转换为Jalali日期格式。像这个

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'}]

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'}]

我认为,您在转换日期时出错了。例如,2022-07-21的日期将不是1401-05-27,而是1401-04-30(如果我错了,请纠正我)

但是,如果我正确地理解了你的问题的本质,那么试着使用方便的库-persiantools

安装:

python -m pip install persiantools

您的字典已输入:

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'}]

使用上述库的程序代码:

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

输出:

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'}]

相关内容

  • 没有找到相关文章

最新更新