How to use the pytz.timezone function in pytz

To help you get started, we’ve selected a few pytz examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github pokerregion / poker / handparser / common.py View on Github external
from abc import ABCMeta, abstractmethod
from collections import MutableMapping
from inspect import ismethod
import pytz


ET = pytz.timezone('US/Eastern')
UTC = pytz.UTC
POKER_ROOMS = {'PokerStars': 'STARS', 'Full Tilt Poker': 'FTP'}
TYPES = {'Tournament': 'TOUR'}
GAMES = {"Hold'em": 'HOLDEM'}
LIMITS = {'No Limit': 'NL', 'NL': 'NL'}


class PokerHand(MutableMapping):
    """Abstract base class for parsers.

    The attributes can be iterated
    The class can read like a dictionary.
    Every attribute default value is None.

    Public attributes:
        poker_room          -- room ID (4 byte max) ex. STARS, FTP
github RohanDoshi2018 / ZeroshotSemanticSegmentation / trainer_fcn.py View on Github external
score, loss, lbl_pred, lbl_true = self.forward(data, target)

            self.optim.zero_grad()
            loss.backward()            
            self.optim.step()

            print("FCN Train Epoch {:<5} | Iteration {:<5} | Loss {:5.5f} | score_fr grad sum {:15.0f} | upscore grad sum {:15.0f} | score sum {:10.5f}".format(
                int(self.epoch), int(batch_idx), float(loss.data[0]), float(self.model.score_fr.weight.grad.sum().data[0]),
                float(self.model.upscore.weight.grad.sum().data[0]), float(score.sum().data[0])))

            metrics = utils.label_accuracy_score(lbl_true.numpy(), lbl_pred, self.n_class)

            # update the training logs
            with open(osp.join(self.log_dir, 'train_log.csv'), 'a') as f:
                elapsed_time = (datetime.datetime.now(pytz.timezone('US/Eastern')) - self.timestamp_start).total_seconds()
                log = [self.epoch, self.iteration] + [loss.data[0]] + list(metrics) + [elapsed_time]
                log = map(str, log)
                f.write(','.join(log) + '\n')

            # write to tensorboard
            self.tb_writer.add_scalar('fcn/train/loss', loss.data[0], self.iteration)
            self.tb_writer.add_scalar('fcn/train/pxl_acc', metrics[0], self.iteration)
            self.tb_writer.add_scalar('fcn/train/class_acc', metrics[1], self.iteration)
            self.tb_writer.add_scalar('fcn/train/mean_iu', metrics[2], self.iteration)
            self.tb_writer.add_scalar('fcn/train/fwavacc', metrics[3], self.iteration)

            self.iteration += 1
github quantopian / trading_calendars / trading_calendars / exchange_calendar_xses.py View on Github external
Exchange calendar for the Singapore Stock Exchange (XSES, SGX).

    Open time: 9:00 Asia/Singapore
    Close time: 17:00 Asia/Singapore

    NOTE: For now, we are skipping the intra-day break from 12:00 to 13:00.

    Due to the complexity around the Singaporean holidays, we are hardcoding
    a list of holidays covering 1986-2020, inclusive.

    TODO: There are a handful of half-days (day before Chinese New Year,
    Christmas Eve, etc.). We will add those later.
    """

    name = "XSES"
    tz = timezone("Asia/Singapore")
    open_times = (
        (None, time(9, 1)),
    )
    close_times = (
        (None, time(15, 0)),
    )

    @property
    def precomputed_holidays(self):
        return precomputed_ses_holidays
github ToolsForHumans / padre / padre / bot.py View on Github external
jobstores['default'] = jobstores['memory']
        try:
            jobstores['sqlalchemy'] = SQLAlchemyJobStore(
                url=self.config.scheduler.db_uri)
        except AttributeError:
            pass
        executors = {}
        try:
            executors['default'] = ThreadPoolExecutor(
                max_workers=self.config.scheduler.max_workers)
        except AttributeError:
            executors['default'] = ThreadPoolExecutor(
                max_workers=default_max_workers)
        sched = BackgroundScheduler(jobstores=jobstores,
                                    executors=executors,
                                    tz=pytz.timezone(self.config.tz))
        sched.add_listener(functools.partial(_done_listener, sched),
                           events.EVENT_JOB_EXECUTED | events.EVENT_JOB_ERROR)
        sched.add_listener(functools.partial(_submitted_listener, sched),
                           events.EVENT_JOB_SUBMITTED)
        sched.add_listener(functools.partial(_modified_listener, sched),
                           events.EVENT_JOB_MODIFIED)
        return sched
github sammyfung / hk0weather / hk0weather / spiders / hkrainfall.py View on Github external
def parse_time(self, timeperiod):
        endtime = re.sub('^.* and ','',timeperiod)
        endtime = re.sub(',.*','',endtime)
        endtime = re.sub('\.','',endtime).upper()
        endtime = re.sub('^0','12',endtime)
        endtime = datetime.combine(datetime.today().date(), datetime.strptime(endtime,"%I:%M %p").time())
        endtime = endtime.replace(tzinfo = pytz.timezone('Etc/GMT-8'))
        return endtime
github akrherz / iem / htdocs / plotting / auto / scripts100 / p167.py View on Github external
def plotter(fdict):
    """ Go """
    pgconn = get_dbconn("asos")
    ctx = get_autoplot_context(fdict, get_description())
    station = ctx["zstation"]
    year = ctx["year"]
    month = ctx["month"]

    tzname = ctx["_nt"].sts[station]["tzname"]
    tzinfo = pytz.timezone(tzname)

    # Figure out the 1rst and last of this month in the local time zone
    sts = utc(year, month, 3)
    sts = sts.astimezone(tzinfo).replace(day=1, hour=0, minute=0)
    ets = (sts + datetime.timedelta(days=35)).replace(day=1)
    days = (ets - sts).days
    data = np.zeros((24, days))

    df = read_sql(
        """
    SELECT valid at time zone %s as ts,
    skyc1, skyc2, skyc3, skyc4, skyl1, skyl2, skyl3, skyl4,
    vsby
    from alldata where station = %s and valid BETWEEN %s and %s
    and vsby is not null and report_type = 2
    ORDER by valid ASC
github mobeigi / fb2cal / src / fb2cal.py View on Github external
def get_next_12_month_epoch_timestamps():
    """ Returns array of epoch timestamps corresponding to the 1st day of the next 12 months starting from the current month.
        For example, if the current date is 2000-05-20, will return epoch for 2000-05-01, 2000-06-01, 2000-07-01 etc for 12 months """
    
    epoch_timestamps = []

    # Facebook timezone seems to use Pacific Standard Time locally for these epochs
    # So we have to convert our 00:00:01 datetime on 1st of month from Pacific to UTC before getting our epoch timestamps
    pdt = pytz.timezone('America/Los_Angeles')
    cur_date = datetime.now()

    # Loop for next 12 months
    for _ in range(12):
        # Reset day to 1 and time to 00:00:01
        cur_date = cur_date.replace(day=1, hour=0, minute=0, second=0, microsecond=0)

        # Convert from Pacific to UTC and store timestamp
        utc_date = pdt.localize(cur_date).astimezone(pytz.utc)
        epoch_timestamps.append(int(utc_date.timestamp()))
        
        # Move cur_date to 1st of next month
        cur_date = cur_date + relativedelta(months=1)
    
    logger.debug(f'Epoch timestamps are: {epoch_timestamps}')
    return epoch_timestamps
github VoteIT / voteit.core / voteit / core / views / feed.py View on Github external
def _format_date(dt):
            # added to convert the datetime to GTM timezone
            tz = pytz.timezone('GMT')
            dt = tz.normalize(dt.astimezone(tz))
            
            """convert a datetime into an RFC 822 formatted date
        
            Input date must be in GMT.
            """
            # Looks like:
            #   Sat, 07 Sep 2002 00:00:01 GMT
            # Can't use strftime because that's locale dependent
            #
            # Isn't there a standard way to do this for Python?  The
            # rfc822 and email.Utils modules assume a timestamp.  The
            # following is based on the rfc822 module.
            return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (
                    ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()],
                    dt.day,
github WilldooIT / Pentaho-reports-for-OpenERP / odoo_addon / pentaho_report_selection_sets / report_formulae.py View on Github external
def localise(self, value):
        if self.env.context.get('tz'):
            value = pytz.timezone('UTC').localize(value, is_dst=False).astimezone(pytz.timezone(self.env.context['tz']))
        return value
github googleads / googleads-python-lib / examples / adwords / v201502 / extensions / add_site_links.py View on Github external
def main(client, campaign_id):
  # Initialize appropriate services.
  campaign_extension_setting_service = client.GetService(
      'CampaignExtensionSettingService', version='v201502')
  customer_service = client.GetService('CustomerService', version='v201502')

  customer_tz = timezone(customer_service.get()['dateTimeZone'])
  time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz)

  # Create the sitelinks
  sitelink1 = {
      'xsi_type': 'SitelinkFeedItem',
      'sitelinkText': 'Store Hours',
      'sitelinkUrl': 'http://www.example.com/storehours'
  }

  # Show the Thanksgiving specials link only from 20 - 27 Nov.
  sitelink2 = {
      'xsi_type': 'SitelinkFeedItem',
      'sitelinkText': 'Thanksgiving Specials',
      'sitelinkUrl': 'http://www.example.com/thanksgiving',
      # The time zone of the start and end date/times must match the time zone
      # of the customer.