2012-07-04 54 views
15

我有一個MySQL數據庫,現在我生成所有的日期時間字段爲models.DateTimeField。有沒有辦法得到timestamp而不是?我希望能夠創建和更新等自動更新等。django中的時間戳字段

django的文檔沒有這個?

回答

15

實際上有一個非常好的和翔實的文章。在這裏: http://ianrolfe.livejournal.com/36017.html

頁面上的解決方案是稍微過時了,所以我做了以下內容:

from django.db import models 
from datetime import datetime 
from time import strftime 

class UnixTimestampField(models.DateTimeField): 
    """UnixTimestampField: creates a DateTimeField that is represented on the 
    database as a TIMESTAMP field rather than the usual DATETIME field. 
    """ 
    def __init__(self, null=False, blank=False, **kwargs): 
     super(UnixTimestampField, self).__init__(**kwargs) 
     # default for TIMESTAMP is NOT NULL unlike most fields, so we have to 
     # cheat a little: 
     self.blank, self.isnull = blank, null 
     self.null = True # To prevent the framework from shoving in "not null". 

    def db_type(self, connection): 
     typ=['TIMESTAMP'] 
     # See above! 
     if self.isnull: 
      typ += ['NULL'] 
     if self.auto_created: 
      typ += ['default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'] 
     return ' '.join(typ) 

    def to_python(self, value): 
     if isinstance(value, int): 
      return datetime.fromtimestamp(value) 
     else: 
      return models.DateTimeField.to_python(self, value) 

    def get_db_prep_value(self, value, connection, prepared=False): 
     if value==None: 
      return None 
     # Use '%Y%m%d%H%M%S' for MySQL < 4.1 
     return strftime('%Y-%m-%d %H:%M:%S',value.timetuple()) 

要使用它,你需要做的是: timestamp = UnixTimestampField(auto_created=True)

在MySQL中,該列應顯示爲: 'timestamp' timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

只有缺點是它只能在MySQL數據庫上工作。但您可以輕鬆修改其他人。

+2

的'get_db_prep_value'功能是過時的,因爲它僅適用於MySQL <4.1上的'TIMESTAMP'列。對於現代版本的MySQL,使用「%Y-%m-%d%H:%M:%S」而不是「%Y%m%d%H%M%S」。 – CoreDumpError

+0

對於django 1.8,您應該實現from_db_value將數據庫值轉換爲您的對象的屬性。 –

0

pip包django-unixdatetimefield提供了一個UnixDateTimeField字段,您可以使用這個開箱即用的(https://pypi.python.org/pypi/django-unixdatetimefield/)。

實例模型:

from django_unixdatetimefield import UnixDateTimeField 

class MyModel(models.Model): 
    created_at = UnixDateTimeField() 

Python的ORM查詢:

>>> m = MyModel() 
>>> m.created_at = datetime.datetime(2015, 2, 21, 19, 38, 32, 209148) 
>>> m.save() 

數據庫:

sqlite> select created_at from mymodel; 
1426967129 

這裏的源代碼,如果有興趣 - https://github.com/Niklas9/django-unixdatetimefield

聲明:我是本pip軟件包的作者。

+1

它有選項__NULL__等? – KVISH

+0

它支持Django中的標準DateTimeField,後者又支持NULL等。請參閱代碼行8 - https://github.com/Niklas9/django-unixdatetimefield/blob/master/django_unixdatetimefield/fields.py – Niklas9

2

要在插入和更新使用這種自動更新:

created = DateTimeField(auto_now_add=True, editable=False, null=False, blank=False) 
last_modified = DateTimeField(auto_now=True, editable=False, null=False, blank=False) 

的DateTimeField字段應存儲UTC(檢查你的數據庫的設置,我知道從Postgres的,有它的情況下)。您可以通過使用模板中l10n和格式:

{{ object.created|date:'SHORT_DATETIME_FORMAT' }} 

秒,因爲Unix的時代:

{{ object.created|date:'U' }} 

https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#date