简体   繁体   中英

How can I store the result of a function stored in variable as a string?

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!!!

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM