Monday 25 June 2012

Fixing datetime.datetime.now() Python call, or set up Django with the correct Timezone

I had a small problem where the datetime.datetime.now() call was giving me the wrong time - in my case, the time was always 1 hour behind.  It turned out that the problem had to do with my Django timezone settings.

This fix is easy, but took my a little Googling to figure out so I thought I'd document it.

To start, step into python and check if your time is sync'ed up to GMT.

$ python
>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2012, 6, 25, 15, 1, 10, 95084)

If everything is ok, then head into you myproject/settings.py file and look out for the line with the parameter ...

TIME_ZONE = [your time zone]

In my case, that line looks like.

TIME_ZONE = 'America/Toronto'

And that's it.  datetime.datetime.now() now returns the right time in my Django code.


Friday 8 June 2012

Django and JSON - Easily Create a JSON Response

A simple guide on how to create a JSON response from Django.

Special thanks to these guys - http://stackoverflow.com/questions/2428092/django-python-creating-a-json-response.

---

some_key = '0'
response_data = dict()
nested_response_data = dict()

nested_response_data['result'] = 'failed'
nested_response_data['message'] = 'You messed up'
response_data[some_key] = nested_response_data

return HttpResponse(json.dumps(response_data), mimetype="application/json")