0

I'm working on an open source script, for AWS snapshots using the boto3 python sdk.

I have a function that returns json, which contains a function:

datetime.datetime(2017, 11, 3, 21, 2, 27, tzinfo=tzlocal())

When I store the results from the json, it stores that function string, rather than the result of that function.

How can I get python3 to execute that function?

(oddly enough when I print that dict time, it shows correct)

This is what my dict looks like:

{'snap-05c84': datetime.datetime(2017, 11, 3, 22, 4, 48, tzinfo=tzlocal()), 'snap-08bcb': datetime.datetime(2017, 11, 3, 21, 2, 27, tzinfo=tzlocal())}

And the code that builds the dict is:

for snap in snaps['Snapshots']:
  snap_id=snap['SnapshotId']
  start_time=snap['StartTime']
  snap_times[snap_id]=start_time

Thanks in advance!!!

zchpit
  • 3,071
  • 4
  • 28
  • 43

2 Answers2

1

You can use eval, to execute code, and get result of it.

However, as I'm looking at your example, why you have that datetime object as string? Probably you wish to have value already there. You can use handler for that:

import datetime
import json

def datetime_handler(x):
    if isinstance(x, datetime.datetime):
        return x.isoformat()
    raise TypeError("Unknown type")

json.dumps(data, default=datetime_handler)

If you don't like isoformat - strftime can be used.

Michał Zaborowski
  • 3,911
  • 2
  • 19
  • 39
0

If I am understanding you correctly, you have a function name that is being stored as a string. If that is the case, you can use solutions provided here Calling a function of a module from a string with the function's name to use that function.

theBrainyGeek
  • 584
  • 1
  • 6
  • 17
  • No, literally the dict has datetime.datetime(2017, 11, 3, 22, 4, 48, tzinfo=tzlocal()) in it, I need the result of that instead. – CloudCoder1 Nov 03 '17 at 22:56