Bladeren bron

Handle timezones correctly with pytz.

tags/v0.1^2
Ben Kurtovic 12 jaren geleden
bovenliggende
commit
4b1d745e2c
2 gewijzigde bestanden met toevoegingen van 15 en 16 verwijderingen
  1. +14
    -16
      earwigbot/commands/time.py
  2. +1
    -0
      setup.py

+ 14
- 16
earwigbot/commands/time.py Bestand weergeven

@@ -20,27 +20,21 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE. # SOFTWARE.


from datetime import datetime, timedelta
from datetime import datetime
from math import floor from math import floor
from time import time from time import time


try:
import pytz
except ImportError:
pytz = None

from earwigbot.commands import BaseCommand from earwigbot.commands import BaseCommand


class Command(BaseCommand): class Command(BaseCommand):
"""Report the current time in any timezone (UTC default), or in beats.""" """Report the current time in any timezone (UTC default), or in beats."""
name = "time" name = "time"
commands = ["time", "beats", "swatch"] 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): def process(self, data):
if data.command in ["beats", "swatch"]: if data.command in ["beats", "swatch"]:
@@ -61,10 +55,14 @@ class Command(BaseCommand):
self.reply(data, "@{0:0>3}".format(beats)) self.reply(data, "@{0:0>3}".format(beats))


def do_time(self, data, timezone): 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: 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)) self.reply(data, "unknown timezone: {0}.".format(timezone))
return 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"))

+ 1
- 0
setup.py Bestand weergeven

@@ -37,6 +37,7 @@ setup(
"pycrypto >= 2.5", # Storing bot passwords and keys "pycrypto >= 2.5", # Storing bot passwords and keys
"GitPython >= 0.3.2.RC1", # Interfacing with git "GitPython >= 0.3.2.RC1", # Interfacing with git
"PyYAML >= 3.10", # Config parsing "PyYAML >= 3.10", # Config parsing
"pytz >= 2012c", # Timezone handling
], ],
test_suite = "tests", test_suite = "tests",
version = __version__, version = __version__,


Laden…
Annuleren
Opslaan