Cole Canning
Cole Canning

Reputation: 237

How to correctly format a datetime with Django and Python

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?

Upvotes: 3

Views: 1057

Answers (1)

Maxime Lorant
Maxime Lorant

Reputation: 36181

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.

Upvotes: 5

Related Questions