我将Django将日期设置为“ UTC”时,PostgreSQL将日期保存在“本地时区”中

时间:2019-02-22 11:22:15

标签: python django postgresql django-models django-rest-framework

我正在尝试以UTC格式保存日期,但是将其保存在我的localtimezone中,直到Django view都可以,但是在.save()之后,它以'本地时区”

我的setting.py

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_TZ = True

model.py

class Career(models.Model):
"""
model for storing all leads from career section of front apps
"""
name = models.CharField(max_length=200)
email = models.CharField(max_length=200)
phone = models.CharField(max_length=20, blank=True, null=True)
status = models.BooleanField(default=1)
created_on = models.DateTimeField(null=True, blank=True)
updated_on = models.DateTimeField(null=True, blank=True)

class Meta:
    db_table = 'career_leads'

我的views文件

class CareerFormApi(APIView):
 def post(self, request):
    career_serializer = CareerPostSerializer(data=request.data)
    career_data = request.data


    if career_serializer.is_valid():
        career_serializer.validated_data['created_on'] = timezone.datetime.now()
        career_serializer.validated_data['updated_on'] = timezone.datetime.now()
        # I am geeting correct time zone here.
         print(timezone.datetime.now()) 


        career_serializer.validated_data['status'] = True

#after save  i check my Database where it saved as my localtime zone

        career_serializer.save() 

        return Response({
            'status': status_code.HTTP_201_CREATED,
            'message': 'Detail has been saved successfully.'
        }, status=status.HTTP_201_CREATED)
    return Response(career_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

PS 。我已经将postgres时区也更改为UTC

set timezone='UTC';

但这没用。

1 个答案:

答案 0 :(得分:6)

如果要更改Postgresql的时区,请执行以下命令:

ALTER USER User_Name SET TimeZone TO 'utc';

并通过以下方法重新启动postgres服务:

sudo service postgresql restart