Eric Blum Eric Blum - 1 month ago 5
Python Question

python: nested dictionary printing datetime as string

Somewhat related to this question

I have a dictionary that looks something like

times = {
'on':
{'start': datetime.time(6, 0, tzinfo=<DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>),
'end': datetime.time(8, 0, tzinfo=<DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>)}
'off':
{'start': datetime.time(10, 0, tzinfo=<DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>),
'end': datetime.time(13, 0, tzinfo=<DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>)}
}


calling
str(times)
gives

In[34]: str(f)
Out[34]: "{'on': {'start': datetime.time(6, 0, tzinfo=<DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>), 'end': datetime.time(8, 0, tzinfo=<DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>)}, 'off': {'start': datetime.time(10, 0, tzinfo=<DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>), 'end': datetime.time(13, 0, tzinfo=<DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>)}}"


when I would like the datetimes to output as

In[37]: str(times['on']['start'])
Out[37]: '06:00:00'


AKA:

"{'on': {'start': '06:00:00, 'end': '08:00:00'}, 'off': {'start': '10:00:00', 'end': '13:00:00'}}"


Is there a way to do this without creating a custom function?

Answer

This will do it:

str({k: {k1: str(v1) for k1, v1 in v.items()} for k, v in times.items()})

Output looks something like this:

"{'on': {'start': '10:01:00', 'end': '10:01:00'}, 'off': {'start': '10:01:00', 'end': '10:01:00'}}"

It's a little gross since you essentially have to un-pack and then re-pack a nested dictionary, but it works. For arbitrarily nested data, you would need a custom function.

Comments