1

A Event class in models.py

class Event(models.Model):
 timestamp = models.DateTimeField()
 message = models.TextField()

  def __unicode__(self):
    return "'%s' at %s" % (self.message, self.timestamp)

   def api_detail(self):
    return {
        'timestamp': str(self.timestamp),
        'description': self.message,

There is UTC time saved in database. but i want to fetch it in localize time. For example timestamp will return : Feb. 14, 2012 , 7 p.m.. This time is in UTC i want to change it into a local time.

Please help me in this matter :)

Amit Pal
  • 10,604
  • 26
  • 80
  • 160

1 Answers1

3

Local time in which time zone? The pytz documentation suggests that once you've decided which zone to use, it's as simple as:

local_time = zone.localize(timestamp)

Note that converting from UTC to local time is unambiguous, whereas the reverse is not.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • It can be from anywhere in world. There is not such a set to defined it. It can't be possible that it first check local timezone and change it automatically :) – Amit Pal Feb 08 '12 at 07:22
  • @shardaPAL: I thought I'd added a comment, but it seems to be lost. I didn't really understand your previous comment - do you mean you want to use whatever the local time zone of the system running the code is? I can't find a way of getting that through pytz, but it may be available somewhere... – Jon Skeet Feb 08 '12 at 07:42
  • yes, It depends on client timezone.It is a web app and i want to show the local time for every client. For this i was successfully to saved UTC time in database. But now i want to fetch it(according to client timezone) – Amit Pal Feb 08 '12 at 07:47
  • 1
    @shardaPAL: If it's a web app then the tricky bit is finding out the client time zone. There's no way of doing that fully automatically and accurately. You could find the current time zone offset and let the user pick from all the time zones with that current offset - but importantly it's *not* going to be just a matter of using the system time zone for the system the code is running on. – Jon Skeet Feb 08 '12 at 08:23