Python timezone test (with pytz and/or zoneinfo) - Render datetime with the appropriate timezone ¶
Note that: Support for pytz is deprecated in Django 4.0 will be removed in Django 5.0
#!/usr/bin/env python3 import datetime try: import pytz except: pytz = None try: import zoneinfo except: zoneinfo = None def get_system_tz(): """ "Get time zone information of the system in Python?" https://stackoverflow.com/questions/1111056/get-time-zone-information-of-the-system-in-python#51296984 Example: print(get_system_tz()) 'CEST' """ return datetime.datetime.now(datetime.timezone.utc).astimezone().tzname() def is_tz_aware(dt): """ "How to check if a datetime object is localized with pytz?" https://stackoverflow.com/questions/5802108/how-to-check-if-a-datetime-object-is-localized-with-pytz#27596917 """ return dt.tzinfo is not None and dt.tzinfo.utcoffset(dt) is not None def print_dt(dt): tz_aware = is_tz_aware(dt) print("%s ... %s tzaware" % (dt.isoformat(), "is" if tz_aware else "is not")) print("\nNaive:") now_naive = datetime.datetime.now() print_dt(now_naive) print("\nApply system tz:") now_tzaware = now_naive.astimezone() print_dt(now_tzaware) if pytz: print("\nApply specific tz using pytz:") now_pacific = now_naive.astimezone(pytz.timezone('US/Pacific')) print_dt(now_pacific) if zoneinfo: print("\nApply specific tz using zoneinfo:") now_santo_domingo = now_naive.astimezone(zoneinfo.ZoneInfo(key='America/Santo_Domingo')) print_dt(now_santo_domingo)
Results:
Naive: 2023-07-25T16:00:26.781075 ... is not tzaware Apply system tz: 2023-07-25T16:00:26.781075+02:00 ... is tzaware Apply specific tz using pytz: 2023-07-25T07:00:26.781075-07:00 ... is tzaware Apply specific tz using zoneinfo: 2023-07-25T10:00:26.781075-04:00 ... is tzaware
Render a datetime with the appropriate (Django) timezone
> dt datetime.datetime(2020, 9, 16, 14, 11, 54, 68168, tzinfo=<UTC>) > dt.strftime("%d/%m/%Y %H:%M:%S") '16/09/2020 14:11:54' > from django.utils import timezone > timezone.localtime(dt) datetime.datetime(2020, 9, 16, 16, 11, 54, 68168, tzinfo=<DstTzInfo 'Europe/Rome' CEST+2:00:00 DST>) > timezone.localtime(dt).strftime("%d/%m/%Y %H:%M:%S") '16/09/2020 16:11:54'