### Create Development Environment Source: https://github.com/regebro/tzlocal/blob/master/README.rst Use this make command to set up a development environment with necessary tools. Ensure a supported Python version is installed first. ```bash $ make devenv ``` -------------------------------- ### Get Local Timezone and Use with Datetime Source: https://context7.com/regebro/tzlocal/llms.txt Obtain the local timezone as a zoneinfo.ZoneInfo object and use it to create timezone-aware datetimes. Demonstrates conversion to UTC and other timezones. ```python from tzlocal import get_localzone from datetime import datetime # Get the local timezone tz = get_localzone() print(tz) # Output: zoneinfo.ZoneInfo(key='America/New_York') # Create a timezone-aware datetime in local time local_dt = datetime(2024, 7, 15, 14, 30, tzinfo=tz) print(local_dt) # Output: 2024-07-15 14:30:00-04:00 # Convert to UTC utc_dt = local_dt.astimezone(datetime.timezone.utc) print(utc_dt) # Output: 2024-07-15 18:30:00+00:00 # Convert to another timezone from zoneinfo import ZoneInfo tokyo = ZoneInfo('Asia/Tokyo') tokyo_dt = local_dt.astimezone(tokyo) print(tokyo_dt) # Output: 2024-07-16 03:30:00+09:00 # Get current time in local timezone now_local = datetime.now(tz) print(f"Current local time: {now_local}") ``` -------------------------------- ### Working with Datetime Objects and Timezones Source: https://context7.com/regebro/tzlocal/llms.txt Examples demonstrating how to use tzlocal with Python's `datetime` module for timezone-aware operations. This includes creating aware datetimes, scheduling events, and converting between timezones. ```python from datetime import datetime, timedelta from tzlocal import get_localzone from zoneinfo import ZoneInfo # Get local timezone local_tz = get_localzone() # Create timezone-aware datetimes now = datetime.now(local_tz) print(f"Local now: {now}") # Schedule something for tomorrow at 9 AM local time tomorrow_9am = datetime( now.year, now.month, now.day, 9, 0, tzinfo=local_tz ) + timedelta(days=1) print(f"Tomorrow 9 AM: {tomorrow_9am}") # Convert between timezones utc = ZoneInfo('UTC') eastern = ZoneInfo('US/Eastern') london = ZoneInfo('Europe/London') meeting_utc = datetime(2024, 12, 15, 15, 0, tzinfo=utc) print(f"Meeting UTC: {meeting_utc}") print(f"Meeting Local: {meeting_utc.astimezone(local_tz)}") print(f"Meeting Eastern: {meeting_utc.astimezone(eastern)}") print(f"Meeting London: {meeting_utc.astimezone(london)}") # Store as UTC, display as local def store_timestamp(): """Store current time as UTC.""" return datetime.now(utc) def display_local(utc_timestamp): """Convert stored UTC timestamp to local time for display.""" return utc_timestamp.astimezone(local_tz) stored = store_timestamp() displayed = display_local(stored) print(f"Stored (UTC): {stored}") print(f"Displayed (Local): {displayed}") ``` -------------------------------- ### Get Local Timezone Source: https://github.com/regebro/tzlocal/blob/master/README.rst Call this function to retrieve the local timezone information. The output will indicate which configuration files were found and their contents. ```python tzlocal.get_localzone() ``` -------------------------------- ### Get Local Timezone Object Source: https://github.com/regebro/tzlocal/blob/master/README.rst Import and call `get_localzone()` to obtain a tzinfo object representing the local timezone. This is the primary way to get local timezone information. ```python from tzlocal import get_localzone tz = get_localzone() tz ``` -------------------------------- ### get_localzone() - Get Local Timezone Object Source: https://context7.com/regebro/tzlocal/llms.txt Retrieves a zoneinfo.ZoneInfo object representing the local timezone. This function is the primary way to get local timezone information and caches results for performance. ```APIDOC ## get_localzone() ### Description Returns a `zoneinfo.ZoneInfo` object representing the local timezone. This is the primary function for obtaining timezone information and will work even when no explicit timezone name is configured by reading the binary `/etc/localtime` file directly. Results are cached for performance. ### Method GET (conceptual) ### Endpoint N/A (Python function) ### Parameters None ### Request Example ```python from tzlocal import get_localzone from datetime import datetime # Get the local timezone tz = get_localzone() print(tz) # Output: zoneinfo.ZoneInfo(key='America/New_York') # Create a timezone-aware datetime in local time local_dt = datetime(2024, 7, 15, 14, 30, tzinfo=tz) print(local_dt) # Output: 2024-07-15 14:30:00-04:00 # Convert to UTC utc_dt = local_dt.astimezone(datetime.timezone.utc) print(utc_dt) # Output: 2024-07-15 18:30:00+00:00 # Convert to another timezone from zoneinfo import ZoneInfo tokyo = ZoneInfo('Asia/Tokyo') tokyo_dt = local_dt.astimezone(tokyo) print(tokyo_dt) # Output: 2024-07-16 03:30:00+09:00 # Get current time in local timezone now_local = datetime.now(tz) print(f"Current local time: {now_local}") ``` ### Response #### Success Response (200) - **tz** (zoneinfo.ZoneInfo) - A `zoneinfo.ZoneInfo` object representing the local timezone. #### Response Example ```json { "tz": "zoneinfo.ZoneInfo(key='America/New_York')" } ``` ``` -------------------------------- ### Get Local Timezone Name and Handle Errors Source: https://context7.com/regebro/tzlocal/llms.txt Retrieve the local IANA timezone name as a string. This function requires an explicitly configured timezone and may raise ZoneInfoNotFoundError if it cannot be determined. ```python from tzlocal import get_localzone_name from zoneinfo import ZoneInfo, ZoneInfoNotFoundError # Get the timezone name try: tz_name = get_localzone_name() print(f"Local timezone: {tz_name}") # Output: Local timezone: America/New_York # Use the name to create a ZoneInfo object yourself tz = ZoneInfo(tz_name) # Store the timezone name in a database or configuration config = {"user_timezone": tz_name} print(config) # Output: {'user_timezone': 'America/New_York'} except ZoneInfoNotFoundError as e: # Fallback when timezone name cannot be determined print(f"Could not determine timezone name: {e}") tz_name = "UTC" ``` -------------------------------- ### get_localzone_name() - Get Local Timezone Name Source: https://context7.com/regebro/tzlocal/llms.txt Retrieves the IANA timezone name as a string (e.g., 'America/New_York'). This function requires an explicitly configured timezone and may raise ZoneInfoNotFoundError. ```APIDOC ## get_localzone_name() ### Description Returns the IANA timezone name as a string (e.g., "America/New_York", "Europe/London"). Unlike `get_localzone()`, this function requires an explicitly configured timezone and may raise `ZoneInfoNotFoundError` if no timezone name can be determined. Use this when you specifically need the timezone name rather than just a tzinfo object. ### Method GET (conceptual) ### Endpoint N/A (Python function) ### Parameters None ### Request Example ```python from tzlocal import get_localzone_name from zoneinfo import ZoneInfo, ZoneInfoNotFoundError # Get the timezone name try: tz_name = get_localzone_name() print(f"Local timezone: {tz_name}") # Output: Local timezone: America/New_York # Use the name to create a ZoneInfo object yourself tz = ZoneInfo(tz_name) # Store the timezone name in a database or configuration config = {"user_timezone": tz_name} print(config) # Output: {'user_timezone': 'America/New_York'} except ZoneInfoNotFoundError as e: # Fallback when timezone name cannot be determined print(f"Could not determine timezone name: {e}") tz_name = "UTC" ``` ### Response #### Success Response (200) - **tz_name** (string) - The IANA timezone name (e.g., "America/New_York"). #### Response Example ```json { "tz_name": "America/New_York" } ``` #### Error Response (ZoneInfoNotFoundError) - **error** (string) - Message indicating that the timezone name could not be determined. ``` -------------------------------- ### Get Local Timezone Name Source: https://github.com/regebro/tzlocal/blob/master/README.rst Use `get_localzone_name()` to retrieve only the IANA timezone name string for the local system. Note that this function may fail on Unix systems if no timezone is configured, unlike `get_localzone()`. ```python from tzlocal import get_localzone_name get_localzone_name() ``` -------------------------------- ### Run Tests Source: https://github.com/regebro/tzlocal/blob/master/README.rst Execute this make command to run the project's tests. ```bash $ make test ``` -------------------------------- ### Check Syntax Source: https://github.com/regebro/tzlocal/blob/master/README.rst Run this make command to check the code syntax. ```bash $ make check ``` -------------------------------- ### Enable Debug Logging for tzlocal Source: https://github.com/regebro/tzlocal/blob/master/README.rst To troubleshoot issues with tzlocal, you can enable debug logging by configuring the `logging` module and importing `tzlocal`. This will provide detailed output about the library's operations. ```python import logging logging.basicConfig(level="DEBUG") import tzlocal ``` -------------------------------- ### Create and Convert Datetime with Local Timezone Source: https://github.com/regebro/tzlocal/blob/master/README.rst After obtaining the local timezone object, you can create timezone-aware datetime objects and convert them to other timezones using the `astimezone()` method. ```python from datetime import datetime from zoneinfo import ZoneInfo tz = get_localzone() dt = datetime(2015, 4, 10, 7, 22, tzinfo=tz) dt eastern = ZoneInfo('US/Eastern') dt.astimezone(eastern) ``` -------------------------------- ### Catching Warnings in tzlocal Source: https://context7.com/regebro/tzlocal/llms.txt Use this pattern to catch warnings instead of raising errors when tzlocal detects issues. Ensure `record=True` is set for `warnings.catch_warnings`. ```python with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") assert_tz_offset(pacific_chatham, error=False) if w: print(f"Warning: {w[0].message}") ``` -------------------------------- ### Enable Debug Logging for Timezone Detection Source: https://context7.com/regebro/tzlocal/llms.txt Enable debug logging to understand tzlocal's timezone detection process. This is useful for troubleshooting configuration issues. Ensure logging is configured before calling `tzlocal` functions. ```python import logging import tzlocal # Enable debug logging before importing/using tzlocal functions logging.basicConfig(level=logging.DEBUG) # Now get the timezone - debug output will show detection process tz = tzlocal.get_localzone() print(f"Detected timezone: {tz}") # Example debug output: # DEBUG:tzlocal:/etc/timezone found, contents: # America/New_York # # DEBUG:tzlocal:/etc/localtime found # DEBUG:tzlocal:2 found: # {'/etc/timezone': 'America/New_York', '/etc/localtime is a symlink to': 'America/New_York'} ``` -------------------------------- ### Reload Local Timezone After System Change Source: https://context7.com/regebro/tzlocal/llms.txt Clears the cached timezone and re-reads system configuration, useful after the system timezone has been changed at runtime. Demonstrates picking up changes made via the TZ environment variable. ```python import os from tzlocal import get_localzone, reload_localzone # Initial timezone tz1 = get_localzone() print(f"Initial: {tz1}") # Output: Initial: zoneinfo.ZoneInfo(key='America/New_York') # Simulate timezone change via environment variable os.environ['TZ'] = 'Europe/London' # Still returns cached value tz2 = get_localzone() print(f"Cached: {tz2}") # Output: Cached: zoneinfo.ZoneInfo(key='America/New_York') # Reload to pick up the change tz3 = reload_localzone() print(f"Reloaded: {tz3}") # Output: Reloaded: zoneinfo.ZoneInfo(key='Europe/London') # Clean up del os.environ['TZ'] reload_localzone() ``` -------------------------------- ### Assert Timezone Offset Correctness Source: https://context7.com/regebro/tzlocal/llms.txt Validates that the detected timezone's UTC offset matches the system's actual UTC offset, helping to detect misconfigurations. Raises ValueError on mismatch by default. ```python from tzlocal import get_localzone, assert_tz_offset from zoneinfo import ZoneInfo import warnings # Verify local timezone is correctly configured local_tz = get_localzone() try: # This should pass for a correctly configured system assert_tz_offset(local_tz) print("Timezone configuration is correct!") except ValueError as e: print(f"Timezone misconfiguration detected: {e}") # Check a different timezone (will fail unless you're actually in that zone) pacific_chatham = ZoneInfo('Pacific/Chatham') try: assert_tz_offset(pacific_chatham) except ValueError as e: print(f"Expected error: {e}") # Output: Timezone offset does not match system offset: 45900 != -14400. # Please, check your config files. ``` -------------------------------- ### reload_localzone() - Reload Timezone Cache Source: https://context7.com/regebro/tzlocal/llms.txt Clears the cached timezone information and re-reads the system configuration. Useful after the system timezone has been changed during runtime. ```APIDOC ## reload_localzone() ### Description Clears the cached timezone and re-reads the system configuration. Call this function after the system timezone has been changed during runtime (e.g., user changes timezone settings or TZ environment variable is modified). Returns the newly loaded `ZoneInfo` object. ### Method POST (conceptual) ### Endpoint N/A (Python function) ### Parameters None ### Request Example ```python import os from tzlocal import get_localzone, reload_localzone # Initial timezone tz1 = get_localzone() print(f"Initial: {tz1}") # Output: Initial: zoneinfo.ZoneInfo(key='America/New_York') # Simulate timezone change via environment variable os.environ['TZ'] = 'Europe/London' # Still returns cached value tz2 = get_localzone() print(f"Cached: {tz2}") # Output: Cached: zoneinfo.ZoneInfo(key='America/New_York') # Reload to pick up the change tz3 = reload_localzone() print(f"Reloaded: {tz3}") # Output: Reloaded: zoneinfo.ZoneInfo(key='Europe/London') # Clean up del os.environ['TZ'] reload_localzone() ``` ### Response #### Success Response (200) - **tz** (zoneinfo.ZoneInfo) - The newly loaded `zoneinfo.ZoneInfo` object representing the local timezone. #### Response Example ```json { "tz": "zoneinfo.ZoneInfo(key='Europe/London')" } ``` ``` -------------------------------- ### Override Timezone with TZ Environment Variable Source: https://context7.com/regebro/tzlocal/llms.txt This function allows executing code within a specified timezone by temporarily setting the `TZ` environment variable. It ensures the original `TZ` setting is restored afterwards and `tzlocal` is reloaded. ```python import os from datetime import datetime from tzlocal import get_localzone, reload_localzone # Override timezone for testing def run_with_timezone(tz_name, func): """Execute a function with a specific timezone.""" original_tz = os.environ.get('TZ') try: os.environ['TZ'] = tz_name reload_localzone() return func() finally: if original_tz: os.environ['TZ'] = original_tz else: os.environ.pop('TZ', None) reload_localzone() def get_current_hour(): tz = get_localzone() return datetime.now(tz).hour # Test application behavior in different timezones ny_hour = run_with_timezone('America/New_York', get_current_hour) tokyo_hour = run_with_timezone('Asia/Tokyo', get_current_hour) print(f"NY hour: {ny_hour}, Tokyo hour: {tokyo_hour}") # TZ can also point to a zoneinfo file # os.environ['TZ'] = ':/usr/share/zoneinfo/America/Chicago' # reload_localzone() # Colon prefix is also supported (Unix convention) os.environ['TZ'] = ':Europe/Berlin' reload_localzone() tz = get_localzone() print(f"Berlin timezone: {tz}") # Output: Berlin timezone: zoneinfo.ZoneInfo(key='Europe/Berlin') ``` -------------------------------- ### assert_tz_offset() - Assert Timezone Offset Source: https://context7.com/regebro/tzlocal/llms.txt Validates that the detected timezone's UTC offset matches the system's actual UTC offset. Raises ValueError on mismatch by default. ```APIDOC ## assert_tz_offset() ### Description Validates that the detected timezone's UTC offset matches the system's actual UTC offset. This helps detect misconfigured systems where the timezone name doesn't match the actual system time. By default raises `ValueError` on mismatch; pass `error=False` to emit a warning instead. ### Method POST (conceptual) ### Endpoint N/A (Python function) ### Parameters - **tz** (zoneinfo.ZoneInfo) - Required - The timezone object to validate. - **error** (boolean) - Optional - If `False`, emits a warning instead of raising a `ValueError` on mismatch. ### Request Example ```python from tzlocal import get_localzone, assert_tz_offset from zoneinfo import ZoneInfo import warnings # Verify local timezone is correctly configured local_tz = get_localzone() try: # This should pass for a correctly configured system assert_tz_offset(local_tz) print("Timezone configuration is correct!") except ValueError as e: print(f"Timezone misconfiguration detected: {e}") # Check a different timezone (will fail unless you're actually in that zone) pacific_chatham = ZoneInfo('Pacific/Chatham') try: assert_tz_offset(pacific_chatham) except ValueError as e: print(f"Expected error: {e}") # Output: Timezone offset does not match system offset: 45900 != -14400. # Please, check your config files. ``` ### Response #### Success Response (200) - **message** (string) - Indicates that the timezone configuration is correct. #### Response Example ```json { "message": "Timezone configuration is correct!" } ``` #### Error Response (ValueError) - **error** (string) - Message detailing the timezone offset mismatch. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.