NHL/NBA: replace pytz dependency

This commit is contained in:
oddluck 2020-02-25 19:45:59 +00:00
parent e0266f6987
commit 33c7a3fc08
5 changed files with 46 additions and 60 deletions

View File

@ -35,6 +35,11 @@ from supybot.commands import optional, wrap
#import supybot.plugins as plugins #import supybot.plugins as plugins
import supybot.ircutils as ircutils import supybot.ircutils as ircutils
import supybot.callbacks as callbacks import supybot.callbacks as callbacks
import httplib2
import json
import pendulum
from xml.etree import ElementTree
try: try:
from supybot.i18n import PluginInternationalization from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('NBA') _ = PluginInternationalization('NBA')
@ -43,13 +48,6 @@ except ImportError:
# without the i18n module # without the i18n module
_ = lambda x: x _ = lambda x: x
import datetime
import dateutil.parser
import httplib2
import json
import pytz
from xml.etree import ElementTree
class NBA(callbacks.Plugin): class NBA(callbacks.Plugin):
"""Get scores from NBA.com.""" """Get scores from NBA.com."""
@ -136,7 +134,12 @@ class NBA(callbacks.Plugin):
if nugget_is_interesting: if nugget_is_interesting:
games_string += ' | {}'.format(nugget) games_string += ' | {}'.format(nugget)
irc.reply(games_string) if date:
date = pendulum.from_format(date, 'YYYYMMDD').to_date_string()
else:
date = pendulum.now().to_date_string()
irc.reply("{0}: {1}".format(date, games_string))
nba = wrap(nba, [optional('somethingWithoutSpaces'), nba = wrap(nba, [optional('somethingWithoutSpaces'),
optional('somethingWithoutSpaces')]) optional('somethingWithoutSpaces')])
@ -669,11 +672,11 @@ class NBA(callbacks.Plugin):
@staticmethod @staticmethod
def _easternTimeNow(): def _easternTimeNow():
return datetime.datetime.now(pytz.timezone('US/Eastern')) return pendulum.now('US/Eastern')
@staticmethod @staticmethod
def _pacificTimeNow(): def _pacificTimeNow():
return datetime.datetime.now(pytz.timezone('US/Pacific')) return pendulum.now('US/Pacific')
@staticmethod @staticmethod
def _ISODateToEasternDate(iso): def _ISODateToEasternDate(iso):
@ -681,8 +684,8 @@ class NBA(callbacks.Plugin):
Eastern-time date. Eastern-time date.
(The default human-readable format for the listing of games). (The default human-readable format for the listing of games).
""" """
date = dateutil.parser.parse(iso) date = pendulum.parse(iso)
date_eastern = date.astimezone(pytz.timezone('US/Eastern')) date_eastern = date.in_tz('US/Eastern')
eastern_date = date_eastern.strftime('%a %m/%d') eastern_date = date_eastern.strftime('%a %m/%d')
return "{}".format(eastern_date) return "{}".format(eastern_date)
@ -692,8 +695,8 @@ class NBA(callbacks.Plugin):
Eastern time formatted with am/pm. Eastern time formatted with am/pm.
(The default human-readable format for the listing of games). (The default human-readable format for the listing of games).
""" """
date = dateutil.parser.parse(iso) date = pendulum.parse(iso)
date_eastern = date.astimezone(pytz.timezone('US/Eastern')) date_eastern = date.in_tz('US/Eastern')
eastern_time = date_eastern.strftime('%-I:%M %p') eastern_time = date_eastern.strftime('%-I:%M %p')
return "{} ET".format(eastern_time) return "{} ET".format(eastern_time)
@ -702,8 +705,8 @@ class NBA(callbacks.Plugin):
"""Convert the ISO date in UTC time that the API outputs into a """Convert the ISO date in UTC time that the API outputs into a
string with a date and Eastern time formatted with am/pm. string with a date and Eastern time formatted with am/pm.
""" """
date = dateutil.parser.parse(iso) date = pendulum.parse(iso)
date_eastern = date.astimezone(pytz.timezone('US/Eastern')) date_eastern = date.in_tz('US/Eastern')
eastern_datetime = date_eastern.strftime('%a %m/%d, %I:%M %p') eastern_datetime = date_eastern.strftime('%a %m/%d, %I:%M %p')
return "{} ET".format(eastern_datetime) return "{} ET".format(eastern_datetime)
@ -723,8 +726,7 @@ class NBA(callbacks.Plugin):
elif date == 'tomorrow': elif date == 'tomorrow':
day_delta = 1 day_delta = 1
# Calculate the day difference and return a string # Calculate the day difference and return a string
date_string = (cls._pacificTimeNow() + date_string = cls._pacificTimeNow().add(days=day_delta).strftime('%Y%m%d')
datetime.timedelta(days=day_delta)).strftime('%Y%m%d')
return date_string return date_string
@classmethod @classmethod
@ -767,12 +769,12 @@ class NBA(callbacks.Plugin):
elif date.replace('-', '').isdigit(): elif date.replace('-', '').isdigit():
try: try:
parsed_date = datetime.datetime.strptime(date, '%Y-%m-%d') parsed_date = pendulum.from_format(date, 'YYYY-MM-DD')
except: except:
raise ValueError('Incorrect date format, should be YYYY-MM-DD') raise ValueError('Incorrect date format, should be YYYY-MM-DD')
# The current API goes back until 2014-10-04. Is it in range? # The current API goes back until 2014-10-04. Is it in range?
if parsed_date.date() < datetime.date(2014, 10, 4): if parsed_date < pendulum.datetime(2014, 10, 4):
raise ValueError('I can only go back until 2014-10-04') raise ValueError('I can only go back until 2014-10-04')
else: else:
raise ValueError('Date is not valid') raise ValueError('Date is not valid')

View File

@ -1 +1 @@
pytz pendulum

View File

@ -21,6 +21,11 @@ from supybot.commands import *
import supybot.plugins as plugins import supybot.plugins as plugins
import supybot.ircutils as ircutils import supybot.ircutils as ircutils
import supybot.callbacks as callbacks import supybot.callbacks as callbacks
import json
import urllib.request
import pendulum
import requests
try: try:
from supybot.i18n import PluginInternationalization from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('NHL') _ = PluginInternationalization('NHL')
@ -29,14 +34,6 @@ except ImportError:
# without the i18n module # without the i18n module
_ = lambda x: x _ = lambda x: x
import datetime
import dateutil.parser
import json
import pytz
import urllib.request
import pendulum
import requests
class NHL(callbacks.Plugin): class NHL(callbacks.Plugin):
"""Get scores from NHL.com.""" """Get scores from NHL.com."""
def __init__(self, irc): def __init__(self, irc):
@ -118,7 +115,7 @@ class NHL(callbacks.Plugin):
irc.reply("No games found for {}".format(team)) irc.reply("No games found for {}".format(team))
return return
try: try:
tdate = datetime.datetime.strptime(games[0], '%Y-%m-%d').strftime('%m/%d/%y') tdate = pendulum.from_format(games[0], 'YYYY-MM-DD').strftime('%m/%d/%y')
games_string_date = ircutils.bold(tdate + ': ') games_string_date = ircutils.bold(tdate + ': ')
except: except:
games_string_date = '' games_string_date = ''
@ -137,7 +134,7 @@ class NHL(callbacks.Plugin):
irc.reply("No games found for {}".format(team)) irc.reply("No games found for {}".format(team))
return return
try: try:
tdate = datetime.datetime.strptime(games[0], '%Y-%m-%d').strftime('%m/%d/%y') tdate = pendulum.from_format(games[0], 'YYYY-MM-DD').strftime('%m/%d/%y')
games_string_date = ircutils.bold(tdate + ': ') games_string_date = ircutils.bold(tdate + ': ')
except: except:
games_string_date = '' games_string_date = ''
@ -198,7 +195,7 @@ class NHL(callbacks.Plugin):
games = self._getTodayTV(team) games = self._getTodayTV(team)
games_string = self._resultTVAsString(games) games_string = self._resultTVAsString(games)
try: try:
tdate = datetime.datetime.strptime(games[0], '%Y-%m-%d').strftime('%m/%d/%y') tdate = pendulum.from_format(games[0], 'YYYY-MM-DD').strftime('%m/%d/%y')
games_string_date = ircutils.bold(tdate + ': ') games_string_date = ircutils.bold(tdate + ': ')
except: except:
games_string_date = '' games_string_date = ''
@ -215,7 +212,7 @@ class NHL(callbacks.Plugin):
return return
games_string = self._resultTVAsString(games) games_string = self._resultTVAsString(games)
try: try:
tdate = datetime.datetime.strptime(games[0], '%Y-%m-%d').strftime('%m/%d/%y') tdate = pendulum.from_format(games[0], 'YYYY-MM-DD').strftime('%m/%d/%y')
games_string_date = ircutils.bold(tdate + ': ') games_string_date = ircutils.bold(tdate + ': ')
except: except:
games_string_date = '' games_string_date = ''
@ -595,10 +592,10 @@ class NHL(callbacks.Plugin):
return today_iso #.replace('-', '') return today_iso #.replace('-', '')
def _easternTimeNow(self): def _easternTimeNow(self):
return datetime.datetime.now(pytz.timezone('US/Eastern')) return pendulum.now('US/Eastern')
def _pacificTimeNow(self): def _pacificTimeNow(self):
return datetime.datetime.now(pytz.timezone('US/Pacific')) return pendulum.now('US/Pacific')
def _convertISODateToTime(self, iso, target='US/Eastern'): def _convertISODateToTime(self, iso, target='US/Eastern'):
"""Convert the ISO date in UTC time that the API outputs into a """Convert the ISO date in UTC time that the API outputs into a
@ -684,17 +681,16 @@ class NHL(callbacks.Plugin):
date_string = pendulum.now('US/Pacific').next(pendulum.SATURDAY).format('YYYY-MM-DD') date_string = pendulum.now('US/Pacific').next(pendulum.SATURDAY).format('YYYY-MM-DD')
return date_string return date_string
# Calculate the day difference and return a string # Calculate the day difference and return a string
date_string = (self._pacificTimeNow() + date_string = self._pacificTimeNow().add(days=day_delta).strftime('%Y-%m-%d')
datetime.timedelta(days=day_delta)).strftime('%Y-%m-%d')
return date_string return date_string
def _checkDateInput(self, date): def _checkDateInput(self, date):
"""Verify that the given string is a valid date formatted as """Verify that the given string is a valid date formatted as
YYYY-MM-DD. Also, the API seems to go back until 2014-10-04, so we YYYY-MM-DD. Also, the API seems to go back until 2014-10-04, so we
will check that the input is not a date earlier than that.""" will check that the input is not a date earlier than that."""
error_string = 'Incorrect date format, should be YYYY-MM-DD' error_string = 'Incorrect date format, should be YYYY-MM-DD'
if date is None: if date is None:
return None return None
@ -702,30 +698,20 @@ class NHL(callbacks.Plugin):
date = self._EnglishDateToDate(date) date = self._EnglishDateToDate(date)
elif date[:3].lower() in self._FUZZY_DAYS: elif date[:3].lower() in self._FUZZY_DAYS:
date = self._EnglishDateToDate(date.lower()) date = self._EnglishDateToDate(date.lower())
# elif date[:3].upper() in self._TEAMS_BY_TRI:
# date = date[:3].upper()
# return date
#try:
# date = dateutil.parser.parse(date)
#except:
# raise ValueError('Incorrect date format, should be YYYY-MM-DD')
#print(date)
if date.isdigit(): if date.isdigit():
try: try:
date = datetime.datetime.strptime(date, '%Y%m%d').strftime('%Y-%m-%d') date = pendulum.from_format(date, 'YYYYMMDD').strftime('%Y-%m-%d')
except: except:
raise ValueError('Incorrect date format, should be YYYY-MM-DD') raise ValueError('Incorrect date format, should be YYYY-MM-DD')
elif date.replace('-','').isdigit(): elif date.replace('-','').isdigit():
try: try:
parsed_date = datetime.datetime.strptime(date, '%Y-%m-%d') parsed_date = pendulum.from_format(date, 'YYYY-MM-DD')
except: except:
raise ValueError('Incorrect date format, should be YYYY-MM-DD') raise ValueError('Incorrect date format, should be YYYY-MM-DD')
elif date.replace('/','').isdigit(): elif date.replace('/','').isdigit():
if len(date.split('/')) == 2: if len(date.split('/')) == 2:
year = '/' + str(datetime.datetime.now().year) year = '/' + str(pendulum.datetime.now().year)
date += year date += year
elif len(date.split('/')) == 3: elif len(date.split('/')) == 3:
if len(date.split('/')[2]) == 2: if len(date.split('/')[2]) == 2:
@ -733,7 +719,7 @@ class NHL(callbacks.Plugin):
else: else:
raise ValueError('Incorrect date format, should be YYYY-MM-DD') raise ValueError('Incorrect date format, should be YYYY-MM-DD')
try: try:
date = datetime.datetime.strptime(date, '%m/%d/%Y').strftime('%Y-%m-%d') date = pendulum.from_format(date, 'MM/DD/YYYY').strftime('%Y-%m-%d')
except: except:
raise ValueError('Incorrect date format, should be YYYY-MM-DD') raise ValueError('Incorrect date format, should be YYYY-MM-DD')
elif '-' not in date and date.isdigit() == False and len(date) > 3: elif '-' not in date and date.isdigit() == False and len(date) > 3:
@ -741,12 +727,12 @@ class NHL(callbacks.Plugin):
return "Incorrect date format, should be YYYY-MM-DD" return "Incorrect date format, should be YYYY-MM-DD"
try: try:
date = date.title() date = date.title()
year = str(datetime.datetime.now().year) year = str(pendulum.datetime.now().year)
date += year date += year
try: try:
date = datetime.datetime.strptime(date, '%d%b%Y').strftime('%Y-%m-%d') date = pendulum.from_format(date, 'DDMMMYYYY').strftime('%Y-%m-%d')
except: except:
date = datetime.datetime.strptime(date, '%b%d%Y').strftime('%Y-%m-%d') date = pendulum.from_format(date, 'MMMDDYYYY').strftime('%Y-%m-%d')
except: except:
raise ValueError('Incorrect date format, should be YYYY-MM-DD') raise ValueError('Incorrect date format, should be YYYY-MM-DD')
#return "Incorrect date format, should be YYYY-MM-DD" #return "Incorrect date format, should be YYYY-MM-DD"

View File

@ -1,3 +1,2 @@
pytz
pendulum pendulum
requests requests

View File

@ -20,7 +20,6 @@ pyimgur
pylyrics3 pylyrics3
pytest pytest
python-dateutil python-dateutil
pytz
requests requests
roman_numerals roman_numerals
textdistance[extras] textdistance[extras]