Assigning datetime to models.DateTimeField seems to drop the time

Go To StackoverFlow.com

0

I was writing a unittest and noticed that I couldn't assign a datetime object to the models.DateTimeField without loosing the time details. I.e:

class Foo(models.Model):
    created = models.DateTimeField(
        editable=False)

my_time = datetime(2012, 01, 02, 1)
print "My Time", Foo.objects.create(created=my_time).created

Prints:

My time 2012-01-02 00:00:00

However if I do

print "My Time", Foo.objects.create(created='2012-01-02 01:00:00').created

I get:

My time 2012-01-02 01:00:00

What's the proper way of assigning a datetime to a models.DateTimeField?

2012-04-04 20:04
by Kit Sunde
I tested your code and it works for me, i can't see any error in your code, too - Jingo 2012-04-04 20:21
What are you shown if you print my_time before the other print line - joshcartme 2012-04-04 20:47
@joshcartme I should've included that. It prints the correct time - Kit Sunde 2012-04-05 03:43
@Jingo Oh? What version of Django are you on exactly - Kit Sunde 2012-04-05 03:43
I am on Django 1.3.1 / Python 2.7. - Jingo 2012-04-05 06:48


0

You are assigning the datetime in the correct way.

If you can come up with a reproducible test case, then this is a bug, and you should file a ticket at http://code.djangoproject.com/

At a minimum, you'll need a complete models.py (including things like import statements), any settings that you need to change from a default settings.py file, and a sequence of commands that you can run from a python shell that illustrate the issue.

The database that you are using will likely relavent -- is this a problem that affects only SQLite, or MySQL, or are you using a third-party database adapter?

If you can get that together, then definitely post a bug report -- the help you will find there will also go towards fixing the underlying issue for everyone else.

2012-04-10 05:08
by Ian Clelland
Ads