22๐
There was actually a very good and informative article on this. Here:
http://ianrolfe.livejournal.com/36017.html
The solution on the page is slightly deprecated, so I did the following:
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())
To use it, all you have to do is:
timestamp = UnixTimestampField(auto_created=True)
In MySQL, the column should appear as:
'timestamp' timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
Only drawback with this is that it only works on MySQL databases. But you can easily modify it for others.
4๐
To automatically update on insert and update use this:
created = DateTimeField(auto_now_add=True, editable=False, null=False, blank=False)
last_modified = DateTimeField(auto_now=True, editable=False, null=False, blank=False)
The DateTimeField should store UTC (check your DB settings, I know from Postgres that there it is the case). You can use l10n
in the templates and format via:
{{ object.created|date:'SHORT_DATETIME_FORMAT' }}
Seconds since Unix Epoch:
{{ object.created|date:'U' }}
See https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#date
- [Django]-Django related_name for field clashes
- [Django]-How do I run tests against a Django data migration?
- [Django]-Images from ImageField in Django don't load in template
3๐
The pip package django-unixdatetimefield provides a UnixDateTimeField field that you can use for this out of the box (https://pypi.python.org/pypi/django-unixdatetimefield/).
Example model:
from django_unixdatetimefield import UnixDateTimeField
class MyModel(models.Model):
created_at = UnixDateTimeField()
Python ORM query:
>>> m = MyModel()
>>> m.created_at = datetime.datetime(2015, 2, 21, 19, 38, 32, 209148)
>>> m.save()
Database:
sqlite> select created_at from mymodel;
1426967129
Hereโs the source code if interested โ https://github.com/Niklas9/django-unixdatetimefield.
Disclaimer: Iโm the author of this pip package.
- [Django]-How do I deploy Django on AWS?
- [Django]-Django models avoid duplicates
- [Django]-How can I chain Django's "in" and "iexact" queryset field lookups?
0๐
django-extensions has a useful TimeStampedModel
: https://django-extensions.readthedocs.io/en/latest/model_extensions.html
- [Django]-Detect mobile, tablet or Desktop on Django
- [Django]-Negating a boolean in Django template
- [Django]-Getting Values of QuerySet in Django