django 时区在多天和多小时内感知

django timezone aware on multiple days and hours

我想创建一个网站来显示锦标赛列表。比赛可以每天多次重复进行。我举个例子:
锦标赛 1:

我想避免口是心非,所以我在日期和时间上使用 m2m:

class Day(models.Model):
    name = models.CharField(max_length=10)
    weekday = models.IntegerField()

    def __unicode__(self):
        return self.name

class Time(models.Model):
    time = models.TimeField()

class Tournament(models.Model):
    name = models.CharField("Tournament name", max_length=200)
    currency = models.CharField(max_length=5, choices=CURRENCIES, default='USD')
    prize = models.DecimalField(max_digits=20, decimal_places=2)
    entry = models.DecimalField(max_digits=20, decimal_places=2, default=0)
    fee = models.DecimalField(max_digits=20, decimal_places=2, default=0)
    password = models.CharField("password", max_length=200, null=True, blank=True)
    tournament_id = models.CharField("Tournament ID", max_length=50, null=True, blank=True)
    number_of_players = models.DecimalField(max_digits=20, decimal_places=0, default='0', null=True, blank=True)
    type = models.ManyToManyField('room.Type')
    room = models.ManyToManyField('room.Room')
    requirements_difficulty = models.IntegerField('Tournament Difficulty',validators=[MinValueValidator(1), MaxValueValidator(30)],null=True, blank=True)
    requirements_text = models.CharField("Requirements Description", default='no requirements', max_length=1000,null=True, blank=True)
    days = models.ManyToManyField(Day, related_name='days')
    times = models.ManyToManyField(Time, related_name='times')

参数比较多,重要的只有最后两个。我创建时间和日期以添加任意数量的小时和日期。

timezone 有问题。 TimeField 不支持时区。我希望用户 select 天然后几个小时。是否有可能以某种方式创建此功能时区感知?

我想我可以将它单独存储在数据库中,然后在 views.py 中创建可识别时区的日期时间对象,对吗?这里最好的方法是什么?

如果您需要将原始日期时间转换为感知数据时间,您可以替换它的 tzinfo

from datetime import datetime
import pytz


>>> _now = datetime.now()  # naive datatime
>>> _now
datetime.datetime(2015, 9, 25, 17, 18, 56, 596488)
>>> _now = _now.replace(tzinfo=pytz.timezone('America/Chicago'))  # aware datetime
>>> _now
datetime.datetime(2015, 9, 25, 17, 16, 36, 991419, tzinfo=<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD>)

仅以 'America/Chicago' 为例,您可以使用自己的时区。

如果您想像在另一个日期时间一样显示一个感知日期时间:

>>> _now
datetime.datetime(2015, 9, 25, 17, 16, 36, 991419, tzinfo=<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD>)
>>> _now.astimezone(pytz.timezone('America/Lima'))
datetime.datetime(2015, 9, 25, 18, 7, 36, 991419, tzinfo=<DstTzInfo 'America/Lima' PET-1 day, 19:00:00 STD>)

最后一行将显示 _now,来自 America/Chicago 时区,如 America/Lima 时间。