Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django set DateTimeField to server's current time

How do I do the equivalent of this SQL in django?

UPDATE table SET timestamp=NOW() WHERE ... 

Particularly I want to set the datetime field using server's builtin function to get the system time from the server that the database was running on and not the time on the client machine.

I know you can execute the raw sql directly but I'm looking for a more portable solution since databases have different functions for getting the current datetime.

Edit: few people mentioned auto_now param. This updates the datetime on every modification while I want to update datetime only on certain occasions.

like image 692
kefeizhou Avatar asked Sep 19 '11 01:09

kefeizhou


People also ask

How do I get the current time in Django?

First, open the views.py file of your Django application and import the datetime module. Next, use the datetime. now() method to get the current date and time value.

How do I change the date automatically changes in a value in Django?

You want to add the auto_now field and set it to True. This will update with the current timestamp each time you update the model.

What is Django default datetime format?

django default date to be in format %d-%m-%Y.


2 Answers

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() 
like image 199
jsz Avatar answered Sep 21 '22 22:09

jsz


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>) 
like image 20
Andrade Avatar answered Sep 17 '22 22:09

Andrade