简体   繁体   English

Django - model 中的时间戳字段

[英]Django - timestamp fields in model

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? 在 django 中的时间戳字段中找到了相同问题的答案,但我认为我遗漏了一些东西 - 不应该在 django 模型中保存时间戳比创建自己的时间戳字段更容易?


I have a model that has a DateTimeField field.我有一个具有DateTimeField字段的 model。 To feed that field, I am using a datetime object.为了提供该字段,我使用了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.但我刚刚意识到datetime时间 object 实际上并不包括时区,所以我最好直接存储时间戳,因为最初我是从时间戳中的 API 获取这些数据的。 Any more straightforward way to do this than in the answer above?有什么比上面的答案更直接的方法吗?

You don't need to use a datetime object to feed to DateTimeField .您不需要使用datetime时间 object 来提供给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.您可以使用auto_now_add=…参数 [Django-doc]auto_now=…参数 [Django-doc]分别存储创建或更新的时间戳。 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,并在所有需要时间戳的模型中继承:

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 .对于datetime时间 object,您可以使用tzinfo包含时区。 For example you can set the timezone to UTC with:例如,您可以使用以下方法将时区设置为UTC

from dateutil.tz import UTC

mynewdatetime = mydatetime.replace(tzinfo=UCT)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM