Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python getting local time zone?

I'm using tzlocal.get_localzone() to get the local time zone. However, on AWS Lambda this returns "local" instead of the actual TZ such as "Americas/New_York" I'm then trying to use the return value with datetime.replace(tzinfo=new_time_zone) however, this fails when passed in as "local"

Does anyone have a trick on how to do this in AWS so my lambda ftn uses the TZ relative to the region its running in, or do I need to escalate this with AWS?

like image 709
user2615236 Avatar asked May 19 '17 18:05

user2615236


People also ask

How do you give timezone in Python?

You can also use the pytz module to create timezone-aware objects. For this, we will store the current date and time in a new variable using the datetime. now() function of datetime module and then we will add the timezone using timezone function of pytz module.

What does timezone NOW () return?

timezone. now() useful. This function returns the current date and time as a naive datetime when USE_TZ = False and as an aware datetime when USE_TZ = True . You can add or subtract datetime.

How do I print UTC time in Python?

Getting the UTC timestampdatetime. now() to get the current date and time. Then use tzinfo class to convert our datetime to UTC. Lastly, use the timestamp() to convert the datetime object, in UTC, to get the UTC timestamp.


1 Answers

You should not use tzlocal in server-side code. It is meant for desktop applications only.

  • Most servers, especially in cloud-based services, set their system time zone to UTC.

  • You have no guarantee that the server's time zone is set to anything in particular (including UTC, or a regional time zone).

  • Your code should not behave differently when running from one cloud environment to the next, or on premises.

This is also described in the timezone best practices article.

like image 92
Matt Johnson-Pint Avatar answered Sep 29 '22 19:09

Matt Johnson-Pint