[Django]-Django set DateTimeField to database server's current time

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()
πŸ‘€jsz

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>)
πŸ‘€Andrade

32πŸ‘

You can use database function Now starting Django 1.9:

from django.db.models.functions import Now
Model.objects.filter(...).update(timestamp=Now())
πŸ‘€tvorog

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()
πŸ‘€Chris

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()
πŸ‘€David Hogan

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()
πŸ‘€Kukosk

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)
πŸ‘€Jay Taylor

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".

πŸ‘€Mel Boyce

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.

πŸ‘€j0ker

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)
πŸ‘€CodeView

Leave a comment