3

I have a model called Data in Django and one of the fields is called time_last_updated. It is initialized as follows:

time_last_updated=timezone.now()

When I query the database (PostgresSQL) manually, the date looks like 2014-02-26 01:42:44.290443+00 which is all fine and as I expected. The problem is that when I take my Data object in a python shell, I get this:

>>> Data.objects.all[0].time_last_updated    
datetime.datetime(2014, 2, 26, 1, 42, 44, 290443, tzinfo=<UTC>)

However, if I immediately try and put this result directly back into the shell as if to create a datetime object form it, I get a SyntaxError at the = right after tzinfo.
How is it possible that Django is returning an object with invalid syntax?

8
  • 1
    It is just how the value of your datetime field is printed on the console. Commented Feb 27, 2014 at 21:00
  • I am not sure what you mean. How can it return an object that had a syntax error? Commented Feb 27, 2014 at 21:03
  • Sorry for not being clear. I mean that it's not supposed to be used for creating datetime objects. It's just a string representation of a datetime object. Data.objects.all[0].time_last_updated is still of a datetime type. Commented Feb 27, 2014 at 21:05
  • Do you have timezone support enabled in your settings file? Is pytz installed? Commented Feb 27, 2014 at 21:06
  • Ok, so it is simply a string representation of the object... oh. It seems weird because if i take out the tzinfo parameter, and then use that to create an object it works. So i guess I am really asking if there is any way to change the default string representation of the datetime object? Commented Feb 27, 2014 at 21:07

1 Answer 1

5

In fact, the datetime use the representation of the object stored in tzinfo when you're printing the datetime object in your Python shell.
Django uses its django.utils.timezone module to initialize dates and so the tzinfo attribute is equal to django.utils.timezone.utc (by default, when you haven't specified any timezone).

When you're looking to the __repr__ of utc you can see:

>>> from django.utils.timezone import utc
>>> repr(utc)
'<UTC>'

Hence the tzinfo=<UTC>. It's a string representation, not a real Python value.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I actually do have a default timezone in my settings.py, and its not utc, but thats a different issue. I appreciate the help! I am working on fixing my problem now and I am going to post my solution later.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.