timlukins
timlukins

Reputation: 2724

How can I easily format the date fields of my GQLQuery to another Timezone?

[Edit] And, I should add, most elegantly? I guess (but not sure how) I could just loop through the results in the python code first and format each date there, but I'd rather only loop once...[\Edit]

In my case British Summer Time (which has just recently kicked in).

At the moment my topmost directly formated date is correct, but the dates in the individual rows of the result are still in UTC (1 hour behind). Example output is a templated page that looks like this (where UTC as returned by datetime.now in this case is 12:42):

Time is now: 13:42 on 05 April, 2012

2012-04-05 13:10:00 Event 234

2012-04-05 13:10:00 Event 235

2012-04-05 13:10:00 Event 236

...

Here's what I'm doing...

from pytz.gae import pytz  # N.B. Using the recommended version of pytz
from datetime import datetime

# Use datetime now (in UTC) to select upcoming events (also stored in UTC)

nowat = datetime.now()
upcoming_events = db.GqlQuery(
  "SELECT * FROM Event WHERE eventdatetime >= :1",nowat)

# Convert time to BST and print to string…

utc = pytz.timezone('UTC')
nowat = utc.localize(nowat)
bst = pytz.timezone('Europe/London')
timenow = nowat.astimezone(bst).strftime("%H:%M on %d %B, %Y")

# Pass results to template for formating… (this is the Django engine)

template_values = {
        'time' : timenow,
        'events' : upcoming_events
 }
path = os.path.join(os.path.dirname(__file__),'html','today.html')
self.response.out.write(template.render(path,template_values))

I thought there might be some magic I could similarly apply in the templating code - but it only seems that the date built-in allows formating of the datetime NOT conversion from UTC.

Template is:

<html>
  <head>
    <link type="text/css" rel="stylesheet" href="/css/main.css" />
  </head>
  <body>
    <p>Time is now: {{ time }}</p>
    <table>
      {% for event in events %} 
        <tr>
          <td> {{ event.eventdatetime }} </td>
          <td> {{ event.name }} </td>
        </tr>
      {% endfor %}  
    </table>
  </body>
</html>

Upvotes: 1

Views: 407

Answers (1)

Hoff
Hoff

Reputation: 39826

with django's template engine, you can use Time zone aware output in templates

example usage from the documentation:

{% load tz %}

{% timezone "Europe/Paris" %}
    Paris time: {{ value }}
{% endtimezone %}

{% timezone None %}
    Server time: {{ value }}
{% endtimezone %}

Upvotes: 1

Related Questions