Import pytz into AWS lambda function

If you don't have access to pytz in your environment, maybe you have access to python-dateutil. In that case you can do:

import datetime
import dateutil.tz

eastern = dateutil.tz.gettz('US/Eastern')
datetime.datetime.now(tz=eastern)

REF. How to get current time in Pacific Timezone when import pytz fails?


You need to install the pytz package so it's available for your lambda. The way you do this is having pip install it into the directory you are going to zip and upload to AWS (i.e. peered with the file containing your lambda function).

pip install -t path/to/your/lambda pytz

Then when you zip it up and upload it, it will be available.

Editing to add that I created a tool to do a lot of this for you - you can find it here: https://github.com/jimjkelly/lambda-deploy


To follow up on @cheframzi's answer to "Package a pytz zip file in the format python/pytz/..." as a Lambda Layer, here is one way to do that.

mkdir python
pip3 install -t python pytz=='2019.2'
zip -r pytz.zip python
rm -rf python

And then you can use aws lambda publish-layer-version --layer-name <layer_name> --zip-file fileb://./pytz.zip to deploy a new version of the layer.

As long as the library is installed at the python/pytz level of the zip file, AWS Lambda should be able to find it. You can also put it inside python/lib/python3.8/site-packages\pytz though for your specific python runtime version per here: https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html