views:

571

answers:

1

I am working on a Django application where I need all the postgres represented datetime fields to be saved in UTC (as they should). When I'm creating models with DateTime fields they database representation is generated as "timestamp with time zone". Although I can manually alter the tables to remove the timezone from the fields, I was wondering if the DateTime model field has the ability to not do that - i.e., create "timestamp with out time zone" for some fields. Is that possible? Or do I have to alter them tables? Thanks, Harel

+2  A: 

The data types for postgres in Django map to the string literal timestamp with time zone, and there doesn't seem to be an option to alter that type.

As far as I'm aware, you have three options:

  1. Take advantage of Django's hook for executing raw sql after the create table statement. To do this create a directory called sql in your app and a file in that directory called mymodel.postgres_psycopg2.sql. Place your alter table statements in there.

  2. Write a custom field to define the modifiers for the timestamp field as you see fit. See "writing custom model fields".

  3. Leave the django field as is, and perform the timezone conversion in your application so that you are absolutely certain you are passing the correct time.

My personal preference for data integrity is #3. Just as with character encodings, where you always want to be sure you know the charset and are handling conversions properly, I feel much more comfortable with dates/times whose attributes (including TZ) are as precisely defined as they can be. You may be certain today that all your input is coming to your app already in UTC, but that may change, particular if the timestamps are supplied by end users. For what it's worth, I'd go the extra mile, convert the timestamp in the app to UTC, and store it in the DB with UTC as the time zone.

Jarret Hardie
Thanks Jarret, I am doing the timezone conversion in my app as it is, since I don't trust anyone with time zones ;o) I intend to store all dates as UTC, and since I know a user's time zone, all user entered dates will be converted to UTC before saving anything to database. However, I'd like to treat creation/modified dates as UTC as well, but it seems like Django will save the time zone offset in the field even though my settings.TIMEZONE is UTC (if I save creation date at nov 25th it would save it as +01 offset since the UK were in DST that time. Hence why i want to kill the db tz info.
Harel
Makes sense... in that case, I'd vote for option #1 above.
Jarret Hardie
Another alternative is to run the server itself in UTC.http://serverfault.com/questions/14685/local-timezones-on-servers-considered-harmful
Harel