save time zone in Django Models

前端 未结 4 1856
抹茶落季
抹茶落季 2021-01-03 20:15

I am creating a form in Django. I have to put a input type field, which only stores the timezone in database(which will be chosen by a user from a drop Down list at form). I

4条回答
  •  梦毁少年i
    2021-01-03 20:47

    The way I do this is using pytz valid timezone names. I adjusted my list to reflect only the ones I need, i.e.

    TIMEZONES = (
        'Canada/Atlantic',
        'Canada/Central',
        'Canada/Eastern',
        'Canada/Mountain',
        'Canada/Pacific',
    )
    

    I then have a location class which sets the timezone as a Char Field as such:

    class Location(models.Model):
        ....
        time_zone = models.CharField(max_length=100, blank=True, null=True, choices=TIMEZONES)  # 64 min
        ....
    

    Notice I set blank & null to True to make the field optional. Take a look at django-timezone-field fields.py for further ideas.

    To use this in my code with pytz, I import timezone:

    from pytz import timezone
    import datetime
    from locations.models import Location # my object that has the time_zone field
    loc = Location.objects.get(pk=1)  #get existing location or your object that has time_zone field
    utc = pytz.utc
    some_utc_date = datetime.datetime(2002, 10, 27, 6, 0, 0).replace(tzinfo=utc) #tz aware
    some_date.astimezone(timezone(loc.time_zone))
    

    Replace datetime.datetime(2002, 10, 27, 6, 0, 0) with the datetime field that corresponds to your location or specific object that has the time_zone field. In my case I store all my date fields in UTC format in a MongoDB collection. When I retrieve the data and want to create human readable output, I use the above method to show the date in the output. You can also create a custom tag to handle this in templates. See pytz doc for more details.

提交回复
热议问题