Snippets

Ilnur Ibragimov Django timezone utils

Created by Ilnur Ibragimov

File timezone.py Added

  • Ignore whitespace
  • Hide word diff
+# -*- coding: utf-8 -*-
+
+from django.utils import timezone as django_tz
+import datetime
+import pytz
+
+UTC = pytz.utc
+EPOCH_START = datetime.datetime(1970, 1, 1, 0, 0, 0).replace(tzinfo=UTC)
+
+def utcfromtimestamp(timestamp):
+    return datetime.datetime.utcfromtimestamp(timestamp).replace(tzinfo=pytz.utc)
+
+def utcfromtimestamp_as_local(timestamp):
+    return to_local_tz(datetime.datetime.utcfromtimestamp(timestamp).replace(tzinfo=pytz.utc))
+
+def now_timestamp():
+    return (now() - EPOCH_START).total_seconds()
+
+def get_tz():
+    return django_tz.get_current_timezone()
+
+
+def now_local():
+    return django_tz.now().astimezone(django_tz.get_current_timezone())
+
+
+def now_utc():
+    return django_tz.now().astimezone(django_tz.utc)
+
+
+def to_local_tz(*args):
+    """
+        Аргументы datetime либо год, месяц, день и т.д для создания datetime
+    """
+    dt = args[0] if len(args) == 1 and isinstance(args[0], datetime.datetime) else datetime.datetime(*args)
+    if django_tz.is_naive(dt):
+        _dt = django_tz.make_aware(dt, django_tz.get_current_timezone())
+    else:
+        _dt = dt
+    return _dt.astimezone(django_tz.get_current_timezone())
+
+
+def get_current_offset():
+    """
+    Returns current UTC offset in seconds
+    """
+    tz = get_tz()
+    return tz.utcoffset(django_tz.now()).total_seconds()
HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.