pythondatetimependulum

How to convert a python's datetime.tzinfo object to a pendulum's Timezone object?


I know I can convert a datetime.datetime to pendulums with

from datetime import datetime,timezone
import pendulum

a = datetime(2021,6,1,tzinfo=timezone.utc)
b = pendulum.instance(a)
b.tzinfo.name # the presence of the attribute 'name' means it's a pendulum timezone
type(b.tzinfo) # pendulum.tz.timezone.FixedTimezone

but I have a standalone datetime.tzinfo , is it possible to convert it to pendulum.tz.timezone.*

a = timezone.utc # well, imagine that it can be any tzinfo
b = pendulum.xxxxx(a) # that gives tome pendum.tz.timezone class

Is there such method?


Solution

  • Looking at the implementation of pendulum.instance() you can tell that it relies on a "private" function _safe_timezone that you can use to convert a tzinfo to a pendulum's timezone. Methods/functions that start with an _ underscore usually indicates that they don't form part of the public API, but the function is there.

    In the case of a tzinfo=timezone.utc the pendulum.instance() will convert the tzinfo object to an offset in hours and pass that to pendulum.datetime which will use pendulum._safe_timezone() to convert it to a pendulum.tz.timezone.FixedTimeZone. But the _safe_timezone() also accepts regular datetime.tzinfo as input.

    a = pendulum._safe_timezone(timezone.utc) #  Timezone('UTC')
    type(a) # pendulum.tz.timezone.FixedTimezone