Bob Spryn
Bob Spryn

Reputation: 17812

Django Admin enter timezone for DateTime and display it in that

I'm going to have users entering events into our admin (Django 1.4). It would be most intuitive if they can enter the date/time and choose the timezone that it will both take place in and display in.

That is to say, I want them to be able to somehow specify "This event will take place at 4:00PM EST on November 2nd", and make sure it displays in that timezone.

The admin doesn't seem to have any ability for handling timezone entry yet or specifying a timezone for a datetime field, so I'm not quite sure how to do this.

Upvotes: 2

Views: 1621

Answers (1)

monkut
monkut

Reputation: 43830

Django added timezone support for model datetime objects in 1.4.

However, I haven't used it and I'm not sure it would allow timezone setting automatically in the admin or when a ModelForm is created.

Its important to understand what's going on, once you have a grasp of what's being done, you may be better off using django's timezone support.

Ignoring the internal django support, I'd attack the problem with something like this:

from pytz import all_timezones, timezone

TIMEZONES = zip(all_timezones, all_timezones)

class EventModel(models.Model):

    dt = models.DateTimeField() # user entry
    tz = models.CharField(max_length=150,
                          choices=TIMEZONES) # user entry

    def get_dt_in_user_timezone(self, user_profile):
        event_tz = timezone(self.tz)
        event_dt = event_tz.localize(self.dt) # assign timezone to datetime

        # convert registered datetime to utc
        # --> This can probably be bypassed
        utc_dt = event_dt.astimezone(pytz.utc) 

        # convert to user's time defined in profile
        user_tz = timezone(user_profile.tz)
        return utc_dt.astimezone(user_tz)

When dealing with timezones in python you're going to need pytz.

Upvotes: 2

Related Questions