Get timezone used by datetime.datetime.fromtimestamp()

前端 未结 4 1518
清酒与你
清酒与你 2020-12-09 02:12

Is it possible, and if yes, how, to get the time zone (i.e. the UTC offset or a datetime.timezone instance with that offset) that is used by datetime.date

4条回答
  •  误落风尘
    2020-12-09 02:58

    From the Python documentation:

    classmethod datetime.fromtimestamp(timestamp, tz=None)

    Return the local date and time corresponding to the POSIX timestamp, such as is returned by time.time(). If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive.

    Else tz must be an instance of a class tzinfo subclass, and the timestamp is converted to tz‘s time zone. In this case the result is equivalent to tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz)).

    The key part of this description as it relates to your question is that when you don't specify a time zone, not only does it use the local time zone, but the result is naive. You seem to want it to be aware.

    This is a particular distinction made by Python, and is discussed right at the very top of the datetime documentation.

    If what you want is a datetime that is aware of the local time zone, try the tzlocal library. It is focused on that particular problem. See also this question.

提交回复
热议问题