70π
As j0ker said, if you want automatic update of the timestamp, use the auto_now
option. E.g. date_modified = models.DateTimeField(auto_now=True)
.
If you want to set the field to now only when the object is first created you should use:
date_modified = models.DateTimeField(auto_now_add=True)
Or if you want to do it manually, isnβt it a simple assignment with python datetime.now()
?
from datetime import datetime
obj.date_modified = datetime.now()
54π
The accepted answer is outdated. Hereβs the current and most simple way of doing so:
>>> from django.utils import timezone
>>> timezone.now()
datetime.datetime(2018, 12, 3, 14, 57, 11, 703055, tzinfo=<UTC>)
- [Django]-Order of Serializer Validation in Django REST Framework
- [Django]-Inject errors into already validated form?
- [Django]-Changing Django settings at runtime
32π
You can use database function Now starting Django 1.9:
from django.db.models.functions import Now
Model.objects.filter(...).update(timestamp=Now())
- [Django]-Django nested transactions β βwith transaction.atomic()β
- [Django]-What is the default order of a list returned from a Django filter call?
- [Django]-Django β limiting query results
8π
Here is how I solved this issue. Hope it saves someone time:
from django.db import models
class DBNow(object):
def __str__(self):
return 'DATABASE NOW()'
def as_sql(self, qn, val):
return 'NOW()', {}
@classmethod
def patch(cls, field):
orig_prep_db = field.get_db_prep_value
orig_prep_lookup = field.get_prep_lookup
orig_db_prep_lookup = field.get_db_prep_lookup
def prep_db_value(self, value, connection, prepared=False):
return value if isinstance(value, cls) else orig_prep_db(self, value, connection, prepared)
def prep_lookup(self, lookup_type, value):
return value if isinstance(value, cls) else orig_prep_lookup(self, lookup_type, value)
def prep_db_lookup(self, lookup_type, value, connection, prepared=True):
return value if isinstance(value, cls) else orig_db_prep_lookup(self, lookup_type, value, connection=connection, prepared=True)
field.get_db_prep_value = prep_db_value
field.get_prep_lookup = prep_lookup
field.get_db_prep_lookup = prep_db_lookup
# DBNow Activator
DBNow.patch(models.DateTimeField)
And then just using the DBNow() as a value where updating and filtering is needed:
books = Book.objects.filter(created_on__gt=DBNow())
or:
book.created_on = DBNow()
book.save()
- [Django]-What is the meaning of bind = True keyword in celery?
- [Django]-How do you get PyPy, Django and PostgreSQL to work together?
- [Django]-How would you create a 'manual' django migration?
5π
You can use something like this to create a custom value to represent the use of the current time on the database:
class DatabaseDependentValue(object):
def setEngine(self, engine):
self.engine = engine
@staticmethod
def Converter(value, *args, **kwargs):
return str(value)
class DatabaseNow(DatabaseDependentValue):
def __str__(self):
if self.engine == 'django.db.backends.mysql':
return 'NOW()'
elif self.engine == 'django.db.backends.postgresql':
return 'current_timestamp'
else:
raise Exception('Unimplemented for engine ' + self.engine)
django_conversions.update({DatabaseNow: DatabaseDependentValue.Converter})
def databaseDependentPatch(cls):
originalGetDbPrepValue = cls.get_db_prep_value
def patchedGetDbPrepValue(self, value, connection, prepared=False):
if isinstance(value, DatabaseDependentValue):
value.setEngine(connection.settings_dict['ENGINE'])
return value
return originalGetDbPrepValue(self, value, connection, prepared)
cls.get_db_prep_value = patchedGetDbPrepValue
And then to be able to use DatabaseNow on a DateTimeField:
databaseDependentPatch(models.DateTimeField)
Which then in turn finally allows you do a nice and clean:
class Operation(models.Model):
dateTimeCompleted = models.DateTimeField(null=True)
# ...
operation = # Some previous operation
operation.dateTimeCompleted = DatabaseNow()
operation.save()
- [Django]-Pytest.mark.parametrize with django.test.SimpleTestCase
- [Django]-Django, Turbo Gears, Web2Py, which is better for what?
- [Django]-Django β iterate number in for loop of a template
4π
My tweaked code works with sqlite, mysql and postgresql and is a bit cleaner than the proposed solutions.
class DBCurrentTimestamp:
def __str__(self):
return 'DATABASE CURRENT_TIMESTAMP()'
def as_sql(self, qn, connection):
return 'CURRENT_TIMESTAMP', {}
@classmethod
def patch(cls, *args):
def create_tweaked_get_db_prep_value(orig_get_db_prep_value):
def get_db_prep_value(self, value, connection, prepared=False):
return value if isinstance(value, cls) else orig_get_db_prep_value(self, value, connection, prepared)
return get_db_prep_value
for field_class in args:
field_class.get_db_prep_value = create_tweaked_get_db_prep_value(field_class.get_db_prep_value)
I activate it @ the end of my models.py file like this:
DBCurrentTimestamp.patch(models.DateField, models.TimeField, models.DateTimeField)
and use it like this:
self.last_pageview = DBCurrentTimestamp()
- [Django]-How can I get the full/absolute URL (with domain) in Django?
- [Django]-Are Django SECRET_KEY's per instance or per app?
- [Django]-What is the difference between static files and media files in Django?
3π
Iβve created a Python Django plugin module which allows you to control the use of CURRENT_TIMESTAMP
on DateTimeField
objects, both in specific cases (see usage
below) as well as automatically for auto_now
and auto_now_add
columns.
django-pg-current-timestamp
GitHub: https://github.com/jaytaylor/django-pg-current-timestamp
PyPi: https://pypi.python.org/pypi/django-pg-current-timestamp
Example usage:
from django_pg_current_timestamp import CurrentTimestamp
mm = MyModel.objects.get(id=1)
mm.last_seen_date = CurrentTimestamp()
mm.save()
## Resulting SQL:
## UPDATE "my_model" SET "last_seen_date" = CURRENT_TIMESTAMP;
print MyModel.objects.filter(last_seen_date__lt=CURRENT_TIME).count()
MyModel.objects.filter(id__in=[1, 2, 3]).update(last_seen_date=CURRENT_TIME)
- [Django]-CharField with fixed length, how?
- [Django]-How to know current name of the database in Django?
- [Django]-"No module named simple" error in Django
2π
If you want the datetime from a foreign server (i.e., not the one hosting the Django application), youβre going to have to peg it manually for a datatime to use. You could use a SQL command like select now();
or something over SSH, like ssh user@host "date +%s"
.
- [Django]-Generating file to download with Django
- [Django]-Suppress "?next=blah" behavior in django's login_required decorator
- [Django]-How do I use django rest framework to send a file in response?
1π
Maybe you should take a look into the documentation:
Modelfields: DateField
The option βauto_nowβ could be just what you are searching for. You can also use it with the DateTimeField. It updates the DateTime each time youβre saving the model. So with that option set for your DateTimeField it should be sufficent to retrieve a data-record and save it again to set the time right.
- [Django]-Why use Django on Google App Engine?
- [Django]-Django filter many-to-many with contains
- [Django]-How to return HTTP 400 response in Django?
0π
When creating the table, the field you want to make date now in field after add data add this code to field
class MyModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
- [Django]-How to combine multiple QuerySets in Django?
- [Django]-In a Django QuerySet, how to filter for "not exists" in a many-to-one relationship
- [Django]-How can I get tox and poetry to work together to support testing multiple versions of a Python dependency?