3

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?

Filipe Aleixo
  • 3,924
  • 3
  • 41
  • 74

1 Answers1

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)
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Aren't those parameters just to register when the instance was created? My intent is to store price data that comes from an API (the timestamp is also coming from the API), such that each instance has fields `time` and `value`. – Filipe Aleixo Jun 13 '20 at 12:55
  • 2
    @FilipeAleixo: well a timestamp often refers to the current time (like a stamp at the post office) :p. That is probably why you get bad search results :p. But if you use `datetime` you should indeed include `tz=...` to specify a timezone. – Willem Van Onsem Jun 13 '20 at 12:59