To make a Python Datetime timezone aware for Django Datetime field. You can use the utc from django.utils.timezone for replacing the tzinfo of Python Datetime but make sure that it is in UTC format. Below is a simple example of how to retrieve the current date and time and make it timezone aware for Django Datetime model field.
from django.db import models from django.utils.timezone import utc import datetime class Foo( models.Model ): #datetime field sample date_posted = models.DateTimeField( auto_now_add=True, blank=True ) def save(self, *args, **kwargs): #the datetime generated by datetime module will now be timezone aware self.last_date_updated = datetime.datetime.utcnow().replace(tzinfo=utc) super(Foo, self).save(*args, **kwargs)
Leave a Reply