We help IT Professionals succeed at work.

convert usd to aud using python CurrencyConverter

enthuguy
enthuguy used Ask the Experts™
on
Hi Python experts

this is reference to this conversation

https://www.experts-exchange.com/questions/29167463/python-convert-currency.html?anchor=a42998667¬ificationFollowed=242733822#a42998667

how to convert "float(amount)" from USD to AUD please :)

#!/usr/bin/env python2.7

import argparse
import boto3
import datetime
from currency_converter import CurrencyConverter

parser = argparse.ArgumentParser()
parser.add_argument('--days', type=int, default=30)
args = parser.parse_args()


now = datetime.datetime.utcnow()
start = (now - datetime.timedelta(days=args.days)).strftime('%Y-%m-%d')
end = now.strftime('%Y-%m-%d')
dtemplate="{:10} {:14} {:40} {:16.10f} {:6} {:10}"
htemplate="{:10} {:14} {:40} {:16} {:6} {:10}"

cd = boto3.client('ce', 'ap-southeast-2')

results = []

token = None
while True:
    if token:
        kwargs = {'NextPageToken': token}
    else:
        kwargs = {}
    data = cd.get_cost_and_usage(TimePeriod={'Start': start, 'End':  end}, Granularity='DAILY', Metrics=['UnblendedCost'], GroupBy=[{'Type': 'DIMENSION', 'Key': 'LINKED_ACCOUNT'}, {'Type': 'DIMENSION', 'Key': 'SERVICE'}], **kwargs)
    results += data['ResultsByTime']
    token = data.get('NextPageToken')
    if not token:
        break

print(htemplate.format("TimePeriod", "LinkedAccount", "Service", "Amount", "Unit", "Estimated"))

for result_by_time in results:
    for group in result_by_time['Groups']:
        amount = group['Metrics']['UnblendedCost']['Amount']
        unit = group['Metrics']['UnblendedCost']['Unit']
        print(dtemplate.format(result_by_time['TimePeriod']['Start'], group['Keys'][0],  group['Keys'][1], float(amount), unit,  result_by_time['Estimated']))

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
print(dtemplate.format(result_by_time['TimePeriod']['Start'], group['Keys'][0],  group['Keys'][1], c.convert(float(amount), 'USD', 'AUD'), unit,  result_by_time['Estimated']))

Open in new window


somewhere on top don't forget these lines as well

from currency_converter import CurrencyConverter
c = CurrencyConverter()

Open in new window

nociSoftware Engineer
Distinguished Expert 2018

Commented:
You can change this:
print(dtemplate.format(result_by_time['TimePeriod']['Start'], group['Keys'][0],  group['Keys'][1], float(amount), unit,  result_by_time['Estimated']))

Open in new window


into:
aud_amount = format(CurrencyConverter(float(amount)),"USD","AUD")
print(dtemplate.format(result_by_time['TimePeriod']['Start'], group['Keys'][0],  group['Keys'][1], aud_mount, unit,  result_by_time['Estimated']))

Open in new window


It can be folded into one line as well...

Author

Commented:
Thanks Kim, Noci,

I have another challenge now.

After introducing this currency in the script. When I execute as root, it works fine
Since I execute via jenkins (non-root) user and my server allows jenkins user to execute only selective files from sudoers file

Error when jenkins user execute it
T
raceback (most recent call last):
  File "/usr/local/bin/aws_cost_explorer.py", line 7, in <module>
    from currency_converter import CurrencyConverter
ImportError: No module named currency_converter

Open in new window


when I printed sys path using

print '\n'.join(sys.path)

/usr/local/bin
/usr/lib/python2.7/site-packages/pip-19.3.1-py2.7.egg
/usr/lib64/python27.zip
/usr/lib64/python2.7
/usr/lib64/python2.7/plat-linux2
/usr/lib64/python2.7/lib-tk
/usr/lib64/python2.7/lib-old
/usr/lib64/python2.7/lib-dynload
/root/.local/lib/python2.7/site-packages
/usr/lib64/python2.7/site-packages
/usr/lib/python2.7/site-packages

Open in new window


after seeing few package loading issues as non-root user, I updated jenkins sudoers file like below still no luck.
export PATH=$PATH:/usr/lib64/python2.7
Defaults env_reset
Defaults env_keep += "PATH PYTHONPATH"
jenkins ALL=(root) NOPASSWD: /usr/local/bin/aws_cost_explorer.py

Open in new window


Without currency module (with only USD), jenkins user executes above py file and generats report fine
nociSoftware Engineer
Distinguished Expert 2018

Commented:
What is the difference in the path between running as root & running as jenkins?
(The Jenkins task can also run on jet another system where the currency module is not available.)
You can also place a copy of the currency modules WITH the package...  [ not preferred though ]

Author

Commented:
Thanks
I can give it a try...could you give me a reference please
"currency modules WITH the package"
nociSoftware Engineer
Distinguished Expert 2018

Commented:
Put the module.py file (and all other stuff if there are subdirectories in the module ) in the same directory...

Author

Commented:
bit advanced for me :P
I couldnt find the module directory


/usr/lib64/python2.7/site-packages
/usr/lib/python2.7/site-packages
nociSoftware Engineer
Distinguished Expert 2018

Commented:
There is two forms:
Either a .py file in the site-packages or a directory there with __init__.py  in it.

try to find the package: find / -type f -iname '*currency_converter*'  -ls and find / -type d -iname '*currency_converter*'  -ls
It should give you the path to the python module file(s).