Django rest-framework:django_filters.DateTimeFilter convert timezone

1.2k Views Asked by At

I use django_filters to filter the date greater than datetime

for example

http://127.0.0.1:8000/movies/?datetimefilter=2014-11-18

But the 2014-11-18 I save is utc time,
So actually the time in my timezone maybe is 2014-11-19
How can I let the timezone convert from utc to Asia/Taipei in my views.py??

Please teach me,Thank you very much

my views.py

class MovieFilter(django_filters.FilterSet):
    datetimefilter = django_filters.DateTimeFilter(name="datetime",lookup_type="gte")    
    class Meta:
        model = Movie
        fields = ['datetimefilter']
2

There are 2 best solutions below

2
On

If you simply want to change the timezone of your project, you can set TIME_ZONE = 'Asia/Taipei' in your settings.py.

If you want to covert the input date from UTC to another timezone (Asia/Taipei), this would do the trick:

First of all, do pip install pytz

Then, you can do something like:

>>> import pytz as tz
>>> import datetime
>>> from django.utils.timezone import *
>>> utc_date = datetime.datetime.strptime('2014-11-18', '%Y-%m-%d')
>>> utc_date
datetime.datetime(2014, 11, 18, 0, 0)
>>> aware_date = make_aware(utc_date, utc)
>>> localtime(aware_date, tz.timezone('Asia/Taipei'))
datetime.datetime(2014, 11, 18, 8, 0, tzinfo=<DstTzInfo 'Asia/Taipei' CST+8:00:00 STD>)

For detailed documentation, see django.utils.timezone

0
On

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