views:

65

answers:

1

I use django, and have two models with a models.DateTimeField(). Sometimes I need a copy of a date - but look at this:

>>>myobject.date = datetime.datetime.now()
>>>print myobject.date
>>>2010-04-27 12:10:43.526277

>>>other_object.date_copy = myobject.date
>>>print other_object.date_copy
>>>2010-04-27 12:10:43

Why are these two dates not identical, and how do I make an excact copy of myobject.date?

Edit:

I made the mistake of oversimplifying the code I used. The following code will replicate the weirdness:

>>>myobject.date = datetime.datetime.now()
>>>print myobject.date
>>>2010-04-27 12:10:43.526277
>>>myobject.save()
>>>myobject_retrieved_from_db = Myobject.objects.get(id=myobject.id) 

>>>other_object.date_copy = myobject_retrieved_from_db.date
>>>print other_object.date_copy
>>>2010-04-27 12:10:43

As Petriborg suggested, the difference in time is caused by storing to the database:

>>>print myobject_retrieved_from_db.date
>>>2010-04-27 12:10:43

Mystery solved.

+2  A: 

What version of python are you using?

Seems to work for me...

In [3]: s = datetime.datetime.now()
In [4]: x = s
In [5]: print s
------> print(s)
2010-04-27 06:37:02.303067
In [6]: print x
------> print(x)
2010-04-27 06:37:02.303067

Are you storing the datetime into a 3rd party structure like an sqldb via django? A time struct is usually of the form { int seconds; int fractional_seconds; } or as a long milliseconds, so it might be that the second part is getting dropped, either by structure, or by down casting...

Petriborg
Yes, I store the datetime to a mysql innodb table, python version 2.6.1
Hobhouse