From 4b1d745e2c89ca93cefaafeb12f7e0981e0ffe48 Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Wed, 4 Jul 2012 01:37:30 -0400 Subject: [PATCH] Handle timezones correctly with pytz. --- earwigbot/commands/time.py | 30 ++++++++++++++---------------- setup.py | 1 + 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/earwigbot/commands/time.py b/earwigbot/commands/time.py index dae1822..53dafe8 100644 --- a/earwigbot/commands/time.py +++ b/earwigbot/commands/time.py @@ -20,27 +20,21 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -from datetime import datetime, timedelta +from datetime import datetime from math import floor from time import time +try: + import pytz +except ImportError: + pytz = None + from earwigbot.commands import BaseCommand class Command(BaseCommand): """Report the current time in any timezone (UTC default), or in beats.""" name = "time" commands = ["time", "beats", "swatch"] - timezones = [ - "UTC": 0, - "EST": -5, - "EDT": -4, - "CST": -6, - "CDT": -5, - "MST": -7, - "MDT": -6, - "PST": -8, - "PDT": -7, - ] def process(self, data): if data.command in ["beats", "swatch"]: @@ -61,10 +55,14 @@ class Command(BaseCommand): self.reply(data, "@{0:0>3}".format(beats)) def do_time(self, data, timezone): - now = datetime.utcnow() + if not pytz: + msg = "this command requires the 'pytz' module: http://pytz.sourceforge.net/" + self.reply(data, msg) + return try: - now += timedelta(hours=self.timezones[timezone]) # Timezone offset - except KeyError: + tzinfo = pytz.timezone(timezone) + except pytz.exceptions.UnknownTimeZoneError: self.reply(data, "unknown timezone: {0}.".format(timezone)) return - self.reply(data, now.strftime("%Y-%m-%d %H:%M:%S") + " " + timezone) + now = pytz.utc.localize(datetime.utcnow()).astimezone(tzinfo) + self.reply(data, now.strftime("%Y-%m-%d %H:%M:%S %Z")) diff --git a/setup.py b/setup.py index 0e32bbd..762bda8 100644 --- a/setup.py +++ b/setup.py @@ -37,6 +37,7 @@ setup( "pycrypto >= 2.5", # Storing bot passwords and keys "GitPython >= 0.3.2.RC1", # Interfacing with git "PyYAML >= 3.10", # Config parsing + "pytz >= 2012c", # Timezone handling ], test_suite = "tests", version = __version__,