【发布时间】:2018-08-21 13:41:47
【问题描述】:
这是我之前的一个问题的后续问题。我有一些字典,我需要查看它们包含的每个值,如果该值是日期时间,我需要以特定方式对其进行格式化。我还需要能够递归到嵌套字典和列表中。这是我目前所拥有的:
def fix_time(in_time):
out_time = '{}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}'.format(in_time.year, in_time.month, in_time.day, in_time.hour, in_time.minute, in_time.second)
return out_time
def fix_recursive(dct):
for key, value in dct.items():
if isinstance(value, datetime.datetime):
mydict[key] = fix_time(value)
elif isinstance(value, dict):
fix_recursive(value)
mydict={
'Field1':'Value1'
'SomeDateField1':1516312413.729,
'Field2':'Value2',
'Field3': [
{
'Subfield3_1':'SubValue1',
'SubDateField3_1':1516312413.729
},
{
'Subfield3_2':'SubValue2',
'SubDateField3_2':1516312413.729
},
{
'Subfield3_3':'SubValue3',
'SubDateField3_3':1516312413.729
}
],
'Field4': {
'Subfield4_1':'SubValue1',
'SubDateField4_1':1516312413.729
}
}
fix_recursive(mydict)
这对于字典和嵌套字典非常有用,但对于列表则不太适用。因此,在上面的示例中,fix_recursive 将更正 SomeDateField1 和 SubDateField4_1,但不会更正 SubDateField3_1、SubDateField3_2 或 SubDateField3_3。此外,由于在获得输入之前我不知道输入会是什么样子,因此我正在尝试创建一个函数,该函数可以获取列出的嵌套 3 或 4 层深的值。
我们将不胜感激。
谢谢!
【问题讨论】:
-
您可能会发现我感兴趣的代码here。另请参阅该答案末尾链接的我的其他代码。
-
完全不相关,但是您的代码中有一个错误 - 您正在更新全局变量
mydict而不是局部变量dct。此外,您可能想了解datetime.strftime()的日期时间格式。最后,您的字典中没有日期时间,只有时间戳(表示为浮点数)。 -
很好看,@brunodesthuilliers!我想我们都犯过一次或两次“改变全局而不是局部”的错误。 :D
-
正如布鲁诺所说,熟悉strftime 是个好主意。除了显式调用
strftime,datetime对象还知道如何使用这些代码格式化自己,因此您可以执行'{:%Y-%m-%d %H:%M:%S}'.format(in_time)之类的操作
标签: python python-3.x nested