datetime - django timezone aware on multiple days and hours -


i create site show list of tournaments. tournament may take place more times per day repeatedly. i'll give example:
tournament 1:

  • monday 16:00
  • monday 18:00
  • tuesday 16:00
  • tuesday 18:00
  • friday 16:00
  • friday 18:00

i avoid duplicity, use m2m on days , times:

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') 

there more parameters, important last two. create times , days add many hours , days wish.

problem timezone. timefield not timezone aware. wanted user select days , hours. somehow possible create functionality timezone aware?

i guess store in db separately , create timezone aware datetime objects in views.py correct? best way here?

if need convert naive datetime aware datatime, can replace 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>) 

using 'america/chicago' example, can use own timezone.

and if want show aware datetime in datetime:

>>> _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>) 

the last line show _now, america/chicago timezone in america/lima time.


Comments