Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 659
Cole Canning Avatar asked Dec 27 '25 20:12

Cole Canning


1 Answers

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.

like image 147
Maxime Lorant Avatar answered Dec 30 '25 08:12

Maxime Lorant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!