Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datetime.now() abnormality - Python

I'm serving a Python app through Django. Within the app I'm storing the classic "created" field within a few tables.

This is how the field looks like within the Django form:

created = models.DateTimeField(blank=True, default=datetime.now())

Unfortunately, datetime.now() is not accurate. In fact in the database I have sets of rows with the exact same timestamp.

The datetime.now() value seems to change every 30-45 minutes.


My Django app is served on Windows Server 2005 behind IIS6.

Help would be amazing!

like image 942
RadiantHex Avatar asked Jun 23 '10 09:06

RadiantHex


3 Answers

This is a common newbie mistake, unfortunately. You have called the datetime.now() method in the definition - this means the default will be the time at which the definition was executed, ie when your server process starts up.

You need to pass the callable instead:

created = models.DateTimeField(blank=True, default=datetime.now)

ie without the calling brackets.

(Or, just use auto_now_add=True).

like image 96
Daniel Roseman Avatar answered Oct 19 '22 07:10

Daniel Roseman


because datetime.now() is being called when your module is initialised and that value is being used for the default.

You want to use the auto_now_add=True parameter

created = models.DateTimeField(auto_now_add=True)

edit: no need for 'blank' if you're setting the auto option.

like image 20
pycruft Avatar answered Oct 19 '22 06:10

pycruft


You don't have auto_now or auto_now_add fields set to True. Consequently, the default value is what's filled in on the form. When the form is sent to the browser. Of course there will be duplicates.

http://docs.djangoproject.com/en/1.2/ref/models/fields/#datetimefield

like image 33
S.Lott Avatar answered Oct 19 '22 08:10

S.Lott