Patch: Display localized time and date with htmltmpl

Lars Ljung lars at matholka.se
Thu Sep 10 22:44:55 EST 2009


Hi,

It doesn't make much sense to display English dates and UTC time on a
Swedish web page. So I patched the code to use the system locale and
timezone.

This works for me. But the locale and timezone settings are global and
might affect other parts of the code. Most calls to strftime() seems to
be safe though (I took care of Rfc822()).

It's ugly to call locale.setlocale() from tmpl.py, I know.

Regards,
Lars Ljung

=== modified file 'planet/shell/tmpl.py'
--- planet/shell/tmpl.py        2009-01-09 08:11:16 +0000
+++ planet/shell/tmpl.py        2009-09-10 12:40:59 +0000
@@ -2,10 +2,15 @@
 import sgmllib, time, os, sys, new, urlparse, re
 from planet import config, feedparser
 import htmltmpl
+import locale, calendar

 voids=feedparser._BaseHTMLProcessor.elements_no_end_tag
 empty=re.compile(r"<((%s)[^>]*)></\2>" % '|'.join(voids))

+# Use local time zone and locale
+time.tzset()
+locale.setlocale(locale.LC_ALL, '')
+
 class stripHtml(sgmllib.SGMLParser):
     "remove all tags from the data"
     def __init__(self, data):
@@ -56,13 +61,16 @@
     return str(stripHtml(value))

 def PlanetDate(value):
+    value = time.localtime(calendar.timegm(value))
     return time.strftime(config.date_format(), value)

 def NewDate(value):
     return time.strftime(config.new_date_format(), value)

 def Rfc822(value):
-    return time.strftime("%a, %d %b %Y %H:%M:%S +0000", value)
+    wday = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
+    mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
'Sep', 'Oct', 'Nov', 'Dec']
+    return '%s, %02d %s %04d %02d:%02d:%02d +0000' % (wday[value[6]],
value[2], mon[value[1]-1], value[0], value[3], value[4], value[5])

 def Rfc3399(value):
     return time.strftime("%Y-%m-%dT%H:%M:%S+00:00", value)




More information about the devel mailing list