A Python module that tries to figure out what your local timezone is

Overview

tzlocal

This Python module returns a tzinfo object with the local timezone information under Unix and Windows. It requires either Python 3.9+ or the backports.tzinfo package, and returns zoneinfo.ZoneInfo objects.

This module attempts to fix a glaring hole in the zoneinfo module, that there is no way to get the local timezone information, unless you know the zoneinfo name, andunder several Linux distros that's hard or impossible to figure out.

With tzlocal you only need to call get_localzone() and you will get a tzinfo object with the local time zone info. On some Unices you will still not get to know what the timezone name is, but you don't need that when you have the tzinfo file. However, if the timezone name is readily available it will be used.

Supported systems

These are the systems that are in theory supported:

  • Windows 2000 and later
  • Any unix-like system with a /etc/localtime or /usr/local/etc/localtime

If you have one of the above systems and it does not work, it's a bug. Please report it.

Please note that if you getting a time zone called local, this is not a bug, it's actually the main feature of tzlocal, that even if your system does NOT have a configuration file with the zoneinfo name of your time zone, it will still work.

You can also use tzlocal to get the name of your local timezone, but only if your system is configured to make that possible. tzlocal looks for the timezone name in /etc/timezone, /var/db/zoneinfo, /etc/sysconfig/clock and /etc/conf.d/clock. If your /etc/localtime is a symlink it can also extract the name from that symlink.

If you need the name of your local time zone, then please make sure your system is properly configured to allow that. If it isn't configured, tzlocal will default to UTC.

Usage

Load the local timezone:

>>> from tzlocal import get_localzone
>>> tz = get_localzone()
>>> tz
<DstTzInfo 'Europe/Warsaw' WMT+1:24:00 STD>

Create a local datetime:

>>> from datetime import datetime
>>> dt = datetime(2015, 4, 10, 7, 22, tzinfo=tz)
>>> dt
datetime.datetime(2015, 4, 10, 7, 22, tzinfo=<DstTzInfo 'Europe/Warsaw' CEST+2:00:00 DST>)

Lookup another timezone with zoneinfo (backports.zoneinfo on Python 3.8 or earlier):

>>> from zoneinfo import ZoneInfo
>>> eastern = ZoneInfo('US/Eastern')

Convert the datetime:

>>> dt.astimezone(eastern)
datetime.datetime(2015, 4, 10, 1, 22, tzinfo=<DstTzInfo 'US/Eastern' EDT-1 day, 20:00:00 DST>)

Maintainer

Contributors

  • Marc Van Olmen
  • Benjamen Meyer
  • Manuel Ebert
  • Xiaokun Zhu
  • Cameris
  • Edward Betts
  • McK KIM
  • Cris Ewing
  • Ayala Shachar
  • Lev Maximov
  • Jakub Wilk
  • John Quarles
  • Preston Landers
  • Victor Torres
  • Jean Jordaan
  • Zackary Welch
  • Mickaël Schoentgen
  • Gabriel Corona
  • Alex Grönholm

(Sorry if I forgot someone)

License

You might also like...
A simple in-process python scheduler library, designed to be integrated seamlessly with the `datetime` standard library.

scheduler A simple in-process python scheduler library, designed to be integrated seamlessly with the datetime standard library. Due to the support of

darts is a Python library for easy manipulation and forecasting of time series.
darts is a Python library for easy manipulation and forecasting of time series.

A python library for easy manipulation and forecasting of time series.

Make Python datetime formatting human readable

Make Python datetime formatting human readable

A simple digital clock made with the help of python
A simple digital clock made with the help of python

Digital-Clock ⏰ Description 📚 ✔️ A simple digital clock made with the help of python. The code is easy to understand and implement. With this reposit

A datetime parser in Python by Ari24-cb24 and NekoFantic

datetimeparser A datetime parser in Python by Ari24-cb24 and NekoFantic V 1.0 Erinnerung für den Parser Auf falsche Eingaben überprüfen Liste an Event

pytz Python historical timezone library and database

pytz Brings the IANA tz database into Python. This library allows accurate and cross platform timezone calculations. pytz contains generated code, and

This contains timezone mapping information for when preprocessed from the geonames data

when-data This contains timezone mapping information for when preprocessed from the geonames data. It exists in a separate repository so that one does

Whole-day timezone comparison

Timezone Converter Compare a full day of your local timezone with foreign ones $ timezone-converter tijuana --zone $ timezone-converter tijuana new_yo

A simple code for plotting figure, colorbar, and cropping with python
A simple code for plotting figure, colorbar, and cropping with python

Python Plotting Tools This repository provides a python code to generate figures (e.g., curves and barcharts) that can be used in the paper to show th

Inkscape extensions for figure resizing and editing
Inkscape extensions for figure resizing and editing

Academic-Inkscape: Extensions for figure resizing and editing This repository contains several Inkscape extensions designed for editing plots. Scale P

Make a Turtlebot3 follow a figure 8 trajectory and create a robot arm and make it follow a trajectory
Make a Turtlebot3 follow a figure 8 trajectory and create a robot arm and make it follow a trajectory

HW2 - ME 495 Overview Part 1: Makes the robot move in a figure 8 shape. The robot starts moving when launched on a real turtlebot3 and can be paused a

Simple function to plot multiple barplots in the same figure.
Simple function to plot multiple barplots in the same figure.

Simple function to plot multiple barplots in the same figure. Supports padding and custom color.

FCurve-Cleaner: Tries to clean your dense mocap graphs like an animator would
FCurve-Cleaner: Tries to clean your dense mocap graphs like an animator would

Tries to clean your dense mocap graphs like an animator would! So it will produce a usable artist friendly result while maintaining the original graph.

A simple malware that tries to explain the logic of computer viruses with Python.
A simple malware that tries to explain the logic of computer viruses with Python.

Simple-Virus-With-Python A simple malware that tries to explain the logic of computer viruses with Python. What Is The Virus ? Computer viruses are ma

Pydocstringformatter - A tool to automatically format Python docstrings that tries to follow recommendations from PEP 8 and PEP 257.

Pydocstringformatter A tool to automatically format Python docstrings that tries to follow recommendations from PEP 8 and PEP 257. See What it does fo

FastAPI-Login tries to provide similar functionality as Flask-Login does.

FastAPI-Login FastAPI-Login tries to provide similar functionality as Flask-Login does. Installation $ pip install fastapi-login Usage To begin we hav

a flask profiler which watches endpoint calls and tries to make some analysis.
a flask profiler which watches endpoint calls and tries to make some analysis.

Flask-profiler version: 1.8 Flask-profiler measures endpoints defined in your flask application; and provides you fine-grained report through a web in

This project uses reinforcement learning on stock market and agent tries to learn trading. The goal is to check if the agent can learn to read tape. The project is dedicated to hero in life great Jesse Livermore.

Reinforcement-trading This project uses Reinforcement learning on stock market and agent tries to learn trading. The goal is to check if the agent can

Comments
  • Fix for issue 127

    Fix for issue 127

    Fixes https://github.com/regebro/tzlocal/issues/127 by adding a break to the while-loop that checks for valid paths from a simlink from /etc/localtime. The behavior of the loop is to check for valid files from the top down like this:

    Example behavior with latest release and /etc/localtime -> /usr/share/zoneinfo/Etc/UTC

    /usr/share/zoneinfo/Etc/UTC usr/share/zoneinfo/Etc/UTC share/zoneinfo/Etc/UTC zoneinfo/Etc/UTC Etc/UTC UTC

    Creates an invalid configuration ('Etc/UTC' and 'UTC' don't match) because both '/usr/share/zoneinfo/Etc/UTC' and '/usr/share/zoneinfo/UTC' exist and are valid configurations:

    {'/etc/sysconfig/clock': 'Etc/UTC', '/etc/localtime is a symlink to': 'UTC'}

    With the while loop breaking on the first valid configuration, the desired behavior is realized:

    /usr/share/zoneinfo/Etc/UTC usr/share/zoneinfo/Etc/UTC share/zoneinfo/Etc/UTC zoneinfo/Etc/UTC Etc/UTC {'/etc/sysconfig/clock': 'Etc/UTC', '/etc/localtime is a symlink to': 'Etc/UTC'}

    Adding the break does not affect the opposite scenario, where the simlink points to /usr/share/zoneinfo/UTC, as the first valid config will still be 'UTC'.

    tests pass:

    coverage: platform linux, python 3.8.10-final-0 Name Stmts Miss Cover

    tzlocal/init.py 4 0 100% tzlocal/unix.py 116 0 100% tzlocal/utils.py 57 1 98% tzlocal/win32.py 69 1 99% tzlocal/windows_tz.py 3 0 100%

    TOTAL 249 2 99%

    opened by mudinthewater 0
  • Please allow timezone in the form CET-1

    Please allow timezone in the form CET-1

    My timezone (CET-1) is not able to express as Continent/City. It would be only true in the time between End of October and End of March.

    There is no timezone that supports them anytime.

    Even more, if I set Etc/CET it does use DST even if not expressed.

    opened by mowgli 2
  • `get_localzone()` returns different types depending on environment

    `get_localzone()` returns different types depending on environment

    I just ran into an issue where on my local machine get_localzone() returns a _PytzShimTimezone() wrapping a ZoneInfo() and providing the unwrap_shim() method, but in an Alpine Docker it returns a datetime.timezone object which does not have that method.

    I've now started to write a wrapper along the lines of

    def get_local_tzinfo() -> ZoneInfo:
        with warnings.catch_warnings():
            tz = get_localzone()
        if hasattr(tz, "unwrap_shim"):
            tz = tz.unwrap_shim()
        elif isinstance(tz, timezone) and tz == timezone.utc:
            tz = ZoneInfo("Etc/UTC")
        return tz
    

    or thought maybe just

    def get_local_tzinfo() -> ZoneInfo:
        zone_name = get_localzone_name()
        if zone_name is None:
            zone_name = "Etc/UTC"
        return ZoneInfo(zone_name)
    

    but felt dirty doing so and am now wondering whether I'm doing something wrong or whether get_localzone() should always return the same type?

    opened by lloesche 1
  • Multiple Conflicting Timezones for Etc/UTC

    Multiple Conflicting Timezones for Etc/UTC

    Python and tzlocal version: tzlocal version 4.2 Python version Python 3.8.5

    OS info: NAME="Amazon Linux" VERSION="2" ID="amzn" ID_LIKE="centos rhel fedora" VERSION_ID="2" PRETTY_NAME="Amazon Linux 2" ANSI_COLOR="0;33" CPE_NAME="cpe:2.3:o:amazon:amazon_linux:2" HOME_URL="https://amazonlinux.com/"

    Stack trace:

    Python 3.8.5 (default, Feb 18 2021, 01:24:20) [GCC 7.3.1 20180712 (Red Hat 7.3.1-12)] on linux Type "help", "copyright", "credits" or "license" for more information.

    import tzlocal l=tzlocal.get_localzone() Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python3.8/site-packages/tzlocal/unix.py", line 203, in get_localzone _cache_tz = _get_localzone() File "/usr/local/lib/python3.8/site-packages/tzlocal/unix.py", line 165, in _get_localzone tzname = _get_localzone_name(_root) File "/usr/local/lib/python3.8/site-packages/tzlocal/unix.py", line 144, in _get_localzone_name raise utils.ZoneInfoNotFoundError(message) tzlocal.utils.ZoneInfoNotFoundError: 'Multiple conflicting time zone configurations found:\n/etc/sysconfig/clock: Etc/UTC\n/etc/localtime is a symlink to: UTC\nFix the configuration, or set the time zone in a TZ environment variable.\n'

    /etc/localtime link:

    ll /etc/localtime lrwxrwxrwx 1 root root 27 Apr 5 00:09 /etc/localtime -> /usr/share/zoneinfo/Etc/UTC

    Etc/UTC is not a simlink: ll /usr/share/zoneinfo/Etc/UTC -rw-r--r-- 8 root root 127 Feb 11 19:04 /usr/share/zoneinfo/Etc/UTC

    and contents of clock file:

    cat /etc/sysconfig/clock ZONE="Etc/UTC" UTC="true"

    When ZONE is set to "Etc/UTC" the stack trace appears. When it's set to just "UTC" tzlocal appears to be fine with it.

    opened by mudinthewater 2
Owner
Lennart Regebro
Lennart Regebro
PyTime is an easy-use Python module which aims to operate date/time/datetime by string.

PyTime PyTime is an easy-use Python module which aims to operate date/time/datetime by string. PyTime allows you using nonregular datetime string to g

Sinux 148 Dec 9, 2022
⌚️Internet Time reference and (eventually) converter site, for planning things with your internet friends who aren't (yet) obsessed with Internet Time 😉

Internet-Ti.me Internet Time reference and (eventually) converter site, for planning things with your internet friends who aren't (yet) obsessed with

Jessica Stokes 17 Nov 2, 2022
A Python 3 library for parsing human-written times and dates

Chronyk A small Python 3 library containing some handy tools for handling time, especially when it comes to interfacing with those pesky humans. Featu

Felix Wiegand 339 Dec 19, 2022
Useful extensions to the standard Python datetime features

dateutil - powerful extensions to datetime The dateutil module provides powerful extensions to the standard datetime module, available in Python. Inst

null 2k Dec 29, 2022
A Python library for dealing with dates

moment A Python library for dealing with dates/times. Inspired by Moment.js and Kenneth Reitz's Requests library. Ideas were also taken from the Times

Zach Williams 709 Dec 9, 2022
Python datetimes made easy

Pendulum Python datetimes made easy. Supports Python 2.7 and 3.4+. >>> import pendulum >>> now_in_paris = pendulum.now('Europe/Paris') >>> now_in_par

Sébastien Eustace 5.3k Jan 6, 2023
Friendly Python Dates

When.py: Friendly Dates and Times Production: Development: User-friendly functions to help perform common date and time actions. Usage To get the syst

Andy Dirnberger 191 Oct 14, 2022
Better dates & times for Python

Arrow: Better dates & times for Python Arrow is a Python library that offers a sensible and human-friendly approach to creating, manipulating, formatt

Arrow 8.2k Jan 5, 2023
python parser for human readable dates

Python parser for human readable dates Key Features • How To Use • Installation • Common use cases • You may also like... • License Key Features Suppo

Scrapinghub 2.2k Jan 8, 2023
Generate and work with holidays in Python

python-holidays A fast, efficient Python library for generating country, province and state specific sets of holidays on the fly. It aims to make dete

Maurizio Montel 881 Dec 29, 2022