Reputation: 4244
Found this answer to the same question here Timestamp fields in django but I think I'm missing something - shouldn't saving timestamps in django models be easier than having to create your own timestamp field?
I have a model that has a DateTimeField
field. To feed that field, I am using a datetime
object. But I have just realized that datetime
object doesn't actually include timezone, so I would be better off just directly storing the timestamp, as originally I'm getting this data from an API in timestamps anyway. Any more straightforward way to do this than in the answer above?
Upvotes: 4
Views: 5482
Reputation: 476557
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)
Upvotes: 6