3

I m trying to save date in UTC format, but it being save in my localtimezone It is okay till Django view but after .save() it stores in database as 'localtimezone'

my 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' 

my views file

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) 

P.S. I have change my postgres timezone as well in to UTC like this

set timezone='UTC'; 

But it didn't work.

3
  • try detaching the timezone from the date field before saving it datetime_field = self.datetime_field.replace(tzinfo=None) Commented Feb 22, 2019 at 11:36
  • @MaheshHViraktamath it solved, just need to restart postgresql after changing the timezone , I was missing that. Commented Feb 22, 2019 at 11:37
  • 1
    My recommendation: either use timestamp with time zone and handle time zones in the database, or use timestamp without time zone, store UTC timestamps there and handle time zones in the application. Don't mix. Commented Feb 22, 2019 at 14:47

1 Answer 1

9

If you want change timezone of Postgresql, go through this command:

ALTER USER User_Name SET TimeZone TO 'utc';

And restart the postgres service through this:

sudo service postgresql restart

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.