pytz and astimezone() cannot be applied to a naive datetime

前端 未结 3 923
一整个雨季
一整个雨季 2020-12-02 20:02

I have a date and I need to make it time zone aware.

local_tz = timezone(\'Asia/Tokyo\')
start_date = \'2012-09-27\'
start_date = datetime.strptime(start_dat         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 20:39

    If you are using Django Rest Framework you could override the DateTimeField class like:

    class DateTimeFieldOverridden(serializers.DateTimeField):
    
    def to_representation(self, value):
        local_tz = pytz.timezone(TIME_ZONE)
        value = local_tz.localize(value)
        return super(DateTimeFieldOverridden, self).to_representation(value)
    

    And you use it like this in your serializer:

    date_time = DateTimeFieldOverridden(format='%d-%b-%Y', read_only=True)
    

    Hope this helps someone.

提交回复
热议问题