5π
β
You donβt need to use a datetime
object to feed to DateTimeField
. You can use the auto_now_add=β¦
parameter [Django-doc] or auto_now=β¦
parameter [Django-doc] to store the timestamp of the creation or update respectively. In the past, there were some problems with that, but to the best of my knowledge, these issues have been fixed.
For example:
class MyModel(models.Model):
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
Or you can specify an abstract base class, and inherit in all models that need timestamps:
class TimestampedModel(models.Model):
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class MyModel(TimestampedModel):
# β¦
pass
For a datetime
object, you can include the timezone with tzinfo
. For example you can set the timezone to UTC
with:
from dateutil.tz import UTC
mynewdatetime = mydatetime.replace(tzinfo=UTC)
Source:stackexchange.com