Search code examples
pythonpython-3.xdatetimetimezonepytz

Convert ZoneInfo to Pytz timezone name


I have a datetime string such as date = "2023-06-16T07:46:00-03:00"

Extracting timezone information from it give me the following results:

>>> formatted_date = datetime.strptime(date, "%Y-%m-%dT%H:%M:%S%z")

>>> formatted_date.tzinfo

datetime.timezone(datetime.timedelta(days=-1, seconds=75600))

>>> formatted_date.tzinfo.tzname(formatted_date)

'UTC-03:00'

The problem is, I need the timezone information to be something like America/Los_Angeles, in order to use with PostgreSQL EXTRACT function.

Is there a package or a function in Pytz that convert this tzinfo to a name such as the example I gave?


Solution

  • FObersteiner commented here about the UTC-03:00 being just an offset and not timezone info.

    With this information I was able to find this stack overflow post that contains a solution to convert the offset to a timezone list.

    For this application it won't matter if the user is in Timezone A or B, if both are the same Offset, I just need a name in order to use the Postgres function, so it works.