[Fixed]-Django : Convert UTC to local time zone in 'Views'

25👍

I created this little function to solve the problem in a project:

import pytz
from django.utils import timezone


def convert_to_localtime(utctime):
  fmt = '%d/%m/%Y %H:%M'
  utc = utctime.replace(tzinfo=pytz.UTC)
  localtz = utc.astimezone(timezone.get_current_timezone())
 return localtz.strftime(fmt)

An used like:

utcdate = convert_to_localtime(date_from_db)

I also installed this app: django-tz-detect

10👍

from django.utils import timezone

local_dt = timezone.localtime(date_from_db) if date_from_db is not None else None

1👍

I had the same problem… interestingly this solution didn’t work for me, here’s my working version:

(In settings.py USE_L10N = False, and USE_TZ = False)

import pytz
import tzlocal

def convert_to_localtime(utc):
  fmt = '%d/%m/%Y %H:%M'
  ltz = tzlocal.get_localzone()
  localtz = utc.replace(tzinfo=pytz.utc).astimezone(ltz)
  return localtz.strftime(fmt)

0👍

You can used middleware for transform the datetime

class Record(models.Model):
uuid = models.UUIDField(primary_key=True, default=uuid4, editable=False)
identification = models.CharField(max_length=255)
first_name = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
time_record = models.DateTimeField(
    blank=False,
    null=True,
)

class Meta:
    verbose_name = "Record"
    verbose_name_plural = "Records"

def __str__(self):
    return f"{self.first_name} {self.last_name} id: {self.identification}"

from django.utils.timezone import activate
class TimezoneMiddleware(MiddlewareMixin):
    def process_request(self, request):
        hour = utc_header(request.headers.get("time", ""))
        try:
            activate("Etc/GMT" + hour)
        except Exception:
            activate("Etc/GMT")

class RecordSerializer(serializers.ModelSerializer):
    class Meta:
        model = Record
        fields = "__all__"
    


class ListCreateRecordview(generics.ListCreateAPIView):
    queryset = Record.objects.order_by(
       "-time_record",
    )
    serializer_class = RecordSerializer

RE_VALIDATE_UTC = "(?<=utc)?((\+|\-)[0-1]{1}[0-9]{1})"
def utc_header(zone_time: str) -> str:
    if zone_time and search(RE_VALIDATE_UTC, zone_time):
        num_zone_time = search(
            RE_VALIDATE_UTC,
            zone_time,
        ).group()

        if num_zone_time.startswith("-"):            
           hours = num_zone_time[:3].replace("-", "+")  

        elif num_zone_time.startswith("+"):            
           hours = num_zone_time[:3].replace("+", "-")  

        else:           
           hours = num_zone_time[:2] 

        if hours[1] == "0":
           hours = hours.replace("0", "")
    else:
        hours = "0"

    return hours
👤puroh

Leave a comment