Python pytz.timezone() Examples

The following are code examples for showing how to use pytz.timezone(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: stregsystemet   Author: f-klubben   File: views.py    (license) View Source Project 7 votes vote down vote up
def razzia_wizard(request):
    if request.method == 'POST':
        return redirect(
            reverse("razzia_view") + "?start={0}-{1}-{2}&end={3}-{4}-{5}&products={6}&username=&razzia_title={7}"
            .format(int(request.POST['start_year']),
                    int(request.POST['start_month']),
                    int(request.POST['start_day']),
                    int(request.POST['end_year']), int(request.POST['end_month']),
                    int(request.POST['end_day']),
                    request.POST.get('products'),
                    request.POST.get('razzia_title')))

    suggested_start_date = timezone.now() - datetime.timedelta(days=-180)
    suggested_end_date = timezone.now()

    start_date_picker = fields.DateField(
        widget=extras.SelectDateWidget(years=[x for x in range(2000, timezone.now().year + 1)]))
    end_date_picker = fields.DateField(
        widget=extras.SelectDateWidget(years=[x for x in range(2000, timezone.now().year + 1)]))

    return render(request, 'admin/stregsystem/razzia/wizard.html',
                  {
                      'start_date_picker': start_date_picker.widget.render("start", suggested_start_date),
                      'end_date_picker': end_date_picker.widget.render("end", suggested_end_date)},
                  ) 
Example 2
Project: sopel-modules   Author: phixion   File: forecast.py    (license) View Source Project 6 votes vote down vote up
def weatherfull(bot, trigger):
    """.weather location - Show the weather at the given location."""
    location = trigger.group(2)
    if not location:
        location, forecast, postal, error = get_forecast(bot,trigger)
    else:
        location, forecast, postal, error = get_forecast(bot,trigger,location)
    if error:
        return
    summary = forecast.json()['currently']['summary']
    temp = get_temp(forecast)
    humidity = forecast.json()['currently']['humidity']
    wind = get_wind(forecast)
    alert = get_alert(forecast)
    uv = get_uv(postal) if postal else ''
    sun = get_sun(forecast.json()['timezone'], forecast.json()['daily']['data'][0])
    bot.say(u'%s: %s, %s, Humidity: %s%%, %s%s%s%s' % (location, summary, temp, round(humidity*100), wind, sun, uv, alert)) 
Example 3
Project: tts-bug-bounty-dashboard   Author: 18F   File: dates.py    (license) View Source Project 6 votes vote down vote up
def businesstimedelta(a, b):
    '''
    Calculate the timedelta between two timezone-aware datetimes.

    Note that due to the fact that the businesstime package doesn't currently
    accept timezone-aware datetimes, we need to convert them to
    timezone-naive ones first.

    For future reference, this issue has been filed at:

        https://github.com/seatgeek/businesstime/issues/18
    '''

    # https://stackoverflow.com/a/5452709
    est = pytz.timezone(BUSINESS_TIMEZONE)
    return _businesstime.businesstimedelta(
        a.astimezone(est).replace(tzinfo=None),
        b.astimezone(est).replace(tzinfo=None),
    ) 
Example 4
Project: v2ex-tornado-2   Author: coderyy   File: css.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
def get(self,theme):
        template_values = {}
        themes = os.listdir(os.path.join(os.path.dirname(__file__),'tpl', 'themes'))
        if theme in themes:
            path = os.path.join(theme, 'style.css')
        else:
            path = os.path.join('default', 'style.css')
        env = Environment(loader=FileSystemLoader(os.path.join(os.path.dirname(__file__),"tpl/themes")))
        template = env.get_template(path)
        output = template.render(template_values)
        expires_date = datetime.datetime.now(pytz.timezone('Asia/Shanghai')) + datetime.timedelta(days=7)
        expires_str = expires_date.strftime("%d %b %Y %H:%M:%S GMT")
        self.add_header("Expires", expires_str)
        self.set_header('Cache-Control', 'max-age=120, must-revalidate')
        self.set_header('Content-type','text/css;charset=UTF-8')
        self.write(output) 
Example 5
Project: sndlatr   Author: Schibum   File: test_tzinfo.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def test_arithmetic(self):
        utc_dt = self.transition_time

        for days in range(-420, 720, 20):
            delta = timedelta(days=days)

            # Make sure we can get back where we started
            dt = utc_dt.astimezone(self.tzinfo)
            dt2 = dt + delta
            dt2 = dt2 - delta
            self.assertEqual(dt, dt2)

            # Make sure arithmetic crossing DST boundaries ends
            # up in the correct timezone after normalization
            utc_plus_delta = (utc_dt + delta).astimezone(self.tzinfo)
            local_plus_delta = self.tzinfo.normalize(dt + delta)
            self.assertEqual(
                    prettydt(utc_plus_delta),
                    prettydt(local_plus_delta),
                    'Incorrect result for delta==%d days.  Wanted %r. Got %r'%(
                        days,
                        prettydt(utc_plus_delta),
                        prettydt(local_plus_delta),
                        )
                    ) 
Example 6
Project: sndlatr   Author: Schibum   File: test_tzinfo.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def testPartialMinuteOffsets(self):
        # utcoffset in Amsterdam was not a whole minute until 1937
        # However, we fudge this by rounding them, as the Python
        # datetime library 
        tz = pytz.timezone('Europe/Amsterdam')
        utc_dt = datetime(1914, 1, 1, 13, 40, 28, tzinfo=UTC) # correct
        utc_dt = utc_dt.replace(second=0) # But we need to fudge it
        loc_dt = utc_dt.astimezone(tz)
        self.assertEqual(
                loc_dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'),
                '1914-01-01 14:00:00 AMT+0020'
                )

        # And get back...
        utc_dt = loc_dt.astimezone(UTC)
        self.assertEqual(
                utc_dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'),
                '1914-01-01 13:40:00 UTC+0000'
                ) 
Example 7
Project: sndlatr   Author: Schibum   File: dates.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def get_timezone(zone=None):
    """Looks up a timezone by name and returns it.  The timezone object
    returned comes from ``pytz`` and corresponds to the `tzinfo` interface and
    can be used with all of the functions of Babel that operate with dates.

    If a timezone is not known a :exc:`LookupError` is raised.  If `zone`
    is ``None`` a local zone object is returned.

    :param zone: the name of the timezone to look up.  If a timezone object
                 itself is passed in, mit's returned unchanged.
    """
    if zone is None:
        return LOCALTZ
    if not isinstance(zone, string_types):
        return zone
    try:
        return _pytz.timezone(zone)
    except _pytz.UnknownTimeZoneError:
        raise LookupError('Unknown timezone %s' % zone) 
Example 8
Project: my-weather-indicator   Author: atareao   File: geocodeapi.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def get_timezoneId(latitude, longitude):
    print('****** Requesting timezone identificacion')
    try:
        json_response = read_json_from_url(
            'http://api.geonames.org/timezoneJSON?lat=%s&lng=%s&\
username=atareao' % (latitude, longitude))
        if json_response and 'timezoneId' in json_response.keys():
            return json_response['timezoneId']
        raise Exception
    except Exception as e:
        print('Error requesting timezone identification: %s' % (str(e)))
        try:
            json_response = read_json_from_url(
                'http://api.timezonedb.com/v2/get-time-zone?\
key=02SRH5M6VFLC&format=json&by=position&lat=%s&lng=%s' % (latitude,
                                                           longitude))
            if json_response is not None and\
                    'status' in json_response.keys() and\
                    json_response['status'] == 'OK':
                return json_response['zoneName']
            raise Exception
        except Exception as e:
            print('Error requesting timezone identification: %s' % (str(e)))
    return None 
Example 9
Project: infi.clickhouse_orm   Author: Infinidat   File: test_simple_fields.py    (license) View Source Project 6 votes vote down vote up
def test_datetime_field(self):
        f = DateTimeField()
        epoch = datetime(1970, 1, 1, tzinfo=pytz.utc)
        # Valid values
        for value in (date(1970, 1, 1), datetime(1970, 1, 1), epoch,
                      epoch.astimezone(pytz.timezone('US/Eastern')), epoch.astimezone(pytz.timezone('Asia/Jerusalem')),
                      '1970-01-01 00:00:00', '1970-01-17 00:00:17', '0000-00-00 00:00:00', 0,
                      '2017-07-26T08:31:05', '2017-07-26T08:31:05Z', '2017-07-26 08:31',
                      '2017-07-26T13:31:05+05', '2017-07-26 13:31:05+0500'):
            dt = f.to_python(value, pytz.utc)
            self.assertEquals(dt.tzinfo, pytz.utc)
            # Verify that conversion to and from db string does not change value
            dt2 = f.to_python(f.to_db_string(dt, quote=False), pytz.utc)
            self.assertEquals(dt, dt2)
        # Invalid values
        for value in ('nope', '21/7/1999', 0.5,
                      '2017-01 15:06:00', '2017-01-01X15:06:00', '2017-13-01T15:06:00'):
            with self.assertRaises(ValueError):
                f.to_python(value, pytz.utc) 
Example 10
Project: love   Author: Yelp   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
def utc_week_limits(utc_dt):
    """Returns US/Pacific start (12:00 am Sunday) and end (11:59 pm Saturday) of the week containing utc_dt, in UTC."""
    local_now = utc_dt.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('US/Pacific'))

    local_week_start = local_now - timedelta(
        days=local_now.weekday() + 1,
        hours=local_now.hour,
        minutes=local_now.minute,
        seconds=local_now.second,
        microseconds=local_now.microsecond,
    )
    local_week_end = local_week_start + timedelta(days=7, minutes=-1)

    utc_week_start = local_week_start.astimezone(pytz.utc).replace(tzinfo=None)
    utc_week_end = local_week_end.astimezone(pytz.utc).replace(tzinfo=None)

    return (utc_week_start, utc_week_end) 
Example 11
Project: health-mosconi   Author: GNUHealth-Mosconi   File: patient_evaluation_report.py    (license) View Source Project 6 votes vote down vote up
def parse(cls, report, objects, data, localcontext):
        Company = Pool().get('company.company')

        timezone = None
        company_id = Transaction().context.get('company')
        if company_id:
            company = Company(company_id)
            if company.timezone:
                timezone = pytz.timezone(company.timezone)

        dt = datetime.now()
        localcontext['print_date'] = datetime.astimezone(dt.replace(
            tzinfo=pytz.utc), timezone)
        localcontext['print_time'] = localcontext['print_date'].time()

        return super(PatientEvaluationReport, cls).parse(report, objects, data, 
            localcontext) 
Example 12
Project: spirit   Author: jgayfer   File: general.py    (license) View Source Project 6 votes vote down vote up
def countdown(self, ctx):
        """Show time until upcoming Destiny 2 releases"""
        manager = MessageManager(self.bot, ctx.author, ctx.channel, ctx.prefix, [ctx.message])
        pst_now = datetime.now(tz=pytz.timezone('US/Pacific'))
        text = ""

        for name, date in constants.RELEASE_DATES:
            diff = date - pst_now
            days = diff.days + 1
            if days == 0:
                text += "{}: Today!\n".format(name)
            elif days == 1:
                text += "{}: Tomorrow!\n".format(name)
            elif days > 1:
                text += "{}: {} days\n".format(name, days)

        if not text:
            text = "There are no concrete dates for our next adventure..."

        countdown = discord.Embed(title="Destiny 2 Countdown", color=constants.BLUE)
        countdown.description = text
        await manager.say(countdown, embed=True, delete=False)
        await manager.clear() 
Example 13
Project: CodingDojo   Author: ComputerSocietyUNB   File: base.py    (license) View Source Project 6 votes vote down vote up
def timezone(self):
        """
        Time zone for datetimes stored as naive values in the database.

        Returns a tzinfo object or None.

        This is only needed when time zone support is enabled and the database
        doesn't support time zones. (When the database supports time zones,
        the adapter handles aware datetimes so Django doesn't need to.)
        """
        if not settings.USE_TZ:
            return None
        elif self.features.supports_timezones:
            return None
        elif self.settings_dict['TIME_ZONE'] is None:
            return timezone.utc
        else:
            # Only this branch requires pytz.
            return pytz.timezone(self.settings_dict['TIME_ZONE']) 
Example 14
Project: CodingDojo   Author: ComputerSocietyUNB   File: timezone.py    (license) View Source Project 6 votes vote down vote up
def localtime(value, timezone=None):
    """
    Converts an aware datetime.datetime to local time.

    Local time is defined by the current time zone, unless another time zone
    is specified.
    """
    if timezone is None:
        timezone = get_current_timezone()
    # If `value` is naive, astimezone() will raise a ValueError,
    # so we don't need to perform a redundant check.
    value = value.astimezone(timezone)
    if hasattr(timezone, 'normalize'):
        # This method is available for pytz time zones.
        value = timezone.normalize(value)
    return value 
Example 15
Project: CodingDojo   Author: ComputerSocietyUNB   File: tz.py    (license) View Source Project 6 votes vote down vote up
def timezone_tag(parser, token):
    """
    Enables a given time zone just for this block.

    The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a
    time zone name, or ``None``. If is it a time zone name, pytz is required.
    If it is ``None``, the default time zone is used within the block.

    Sample usage::

        {% timezone "Europe/Paris" %}
            It is {{ now }} in Paris.
        {% endtimezone %}
    """
    bits = token.split_contents()
    if len(bits) != 2:
        raise TemplateSyntaxError("'%s' takes one argument (timezone)" %
                                  bits[0])
    tz = parser.compile_filter(bits[1])
    nodelist = parser.parse(('endtimezone',))
    parser.delete_first_token()
    return TimezoneNode(nodelist, tz) 
Example 16
Project: ibstract   Author: jesseliu0   File: brokers.py    (license) View Source Project 6 votes vote down vote up
def req_hist_data_async(self, *req_list: [object]):
        """
        Concurrently downloads historical market data for multiple requests.
        """
        ibparms_list = (self._hist_data_req_to_args(req) for req in req_list)
        bars_list = await asyncio.gather(*(
            self.reqHistoricalDataAsync(*ibparms)
            for ibparms in ibparms_list))
        df_list = [ib_insync.util.df(bars) for bars in bars_list]
        xchg_tz_list = await asyncio.gather(*(
            self.hist_data_req_timezone(req) for req in req_list))
        blk_list = []
        for req, df, xchg_tz in zip(req_list, df_list, xchg_tz_list):
            _logger.debug(df.iloc[:3])
            if req.BarSize[-1] in ('d', 'W', 'M'):  # not intraday
                dl_tz = xchg_tz  # dates without timezone, init with xchg_tz.
            else:
                dl_tz = pytz.UTC
            blk = MarketDataBlock(df, symbol=req.Symbol, datatype=req.DataType,
                                  barsize=req.BarSize, tz=dl_tz)
            blk.tz_convert(xchg_tz)
            blk_list.append(blk)
        return blk_list 
Example 17
Project: pycon2017_tutorial   Author: Bill-Park   File: calendar_api.py    (license) View Source Project 6 votes vote down vote up
def get_calendar_list(time_min=None):

    if time_min is None:
        time_min = datetime.datetime.now(tz=pytz.timezone('Asia/Seoul')).isoformat('T')

    eventsResult = DRIVE.events().list(
            calendarId='primary', maxResults=10, singleEvents=True,
            orderBy='startTime', timeMin=time_min).execute()

    for item in eventsResult['items']:
        print(item['summary'])
        print(item['start'])
        print(item['end'])

    return eventsResult['items']


# add event 
Example 18
Project: pdpdmeetup   Author: mattharley   File: views.py    (license) View Source Project 6 votes vote down vote up
def get_events(event_status): 
    client = meetup.api.Client('73c42797541a6c207a2a2b41262a66')

    group_info = client.GetGroup({'urlname': 'Perth-Django-Users-Group'})
    group_events = client.GetEvents({'group_id': group_info.id, 'status': event_status})

    return [
        {
            'group_id': group_info.id,
            'event_id': event['id'],
            'event_name': event['name'],
            'event_address': event['venue']['address_1'],
            'event_description': event['description'],
            'og_event_description': strip_tags(event['description']).encode('ascii', 'ignore'),
            'event_yes_rsvp_count': event['yes_rsvp_count'],
            'event_datetime': datetime.datetime.fromtimestamp(event['time'] / 1000.0, pytz.timezone('Australia/Perth'))
        }
        for event in reversed(group_events.results)
    ] 
Example 19
Project: aztro   Author: sameerkumar18   File: signs.py    (license) View Source Project 6 votes vote down vote up
def get_day_based_on_tz(day, tz):
    """Gets the client date() based on tz passed as parameter.
    """
    server_day = datetime.now(tz=pytz.timezone(SERVER_TIMEZONE))
    if tz is not None and tz in pytz.all_timezones:
        client_day = server_day.astimezone(pytz.timezone(tz)).date()
        # else not necessary, same day
        asked = TIMEDELTA_DAYS[day]
        asked_date = client_day + timedelta(days=asked)
        if asked_date > server_day.date():
            day = 'tomorrow'
        elif asked_date < server_day.date():
            day = 'yesterday'
        elif asked == -1 and asked_date == server_day.date():
            day = 'today'
    return day 
Example 20
Project: blazar-dashboard   Author: openstack   File: forms.py    (license) View Source Project 6 votes vote down vote up
def clean(self):
        cleaned_data = super(CreateForm, self).clean()
        local = timezone(self.request.session.get(
            'django_timezone',
            self.request.COOKIES.get('django_timezone', 'UTC')))

        if cleaned_data['start_date']:
            cleaned_data['start_date'] = local.localize(
                cleaned_data['start_date'].replace(tzinfo=None)
            ).astimezone(timezone('UTC'))
        else:
            cleaned_data['start_date'] = datetime.datetime.utcnow()
        if cleaned_data['end_date']:
            cleaned_data['end_date'] = local.localize(
                cleaned_data['end_date'].replace(tzinfo=None)
            ).astimezone(timezone('UTC'))
        else:
            cleaned_data['end_date'] = (cleaned_data['start_date']
                                        + datetime.timedelta(days=1)) 
Example 21
Project: arisu   Author: Appleman1234   File: time.py    (license) View Source Project 6 votes vote down vote up
def time(self, msg, args):
        """Time with timezone or location as parameter"""
        if not args:
            return 'Am I supposed to guess the location?...'
        if len(args) == 1 and args[0].lower() == 'utc':
            tz_name = 'UTC'
        elif len(args) == 1:
            place = args[0] 
            tz_name = self.find_tz(place)
        else:
            place = '_'.join([word.capitalize() for word in args])
            tz_name = self.find_tz(place)

        if not tz_name:
            result = 'Sorry cannot find the timezone for this location'   
        else:
            result = self.get_time_for_timezone(tz_name)
        return result 
Example 22
Project: Python-GUI-Programming-Cookbook-Second-Edition   Author: PacktPublishing   File: Callbacks_Refactored.py    (license) View Source Project 6 votes vote down vote up
def getDateTime(self):
        fmtStrZone = "%Y-%m-%d %H:%M:%S %Z%z"
        # Get Coordinated Universal Time
        utc = datetime.now(timezone('UTC'))
        self.oop.log.writeToLog(utc.strftime(fmtStrZone), 
                                self.oop.level.MINIMUM)
        
        # Convert UTC datetime object to Los Angeles TimeZone
        la = utc.astimezone(timezone('America/Los_Angeles'))
        self.oop.log.writeToLog(la.strftime(fmtStrZone), 
                                self.oop.level.NORMAL)

        # Convert UTC datetime object to New York TimeZone
        ny = utc.astimezone(timezone('America/New_York'))
        self.oop.log.writeToLog(ny.strftime(fmtStrZone), 
                                self.oop.level.DEBUG)
        
        # update GUI label with NY Time and Zone       
        self.oop.lbl2.set(ny.strftime(fmtStrZone)) 
Example 23
Project: Python-GUI-Programming-Cookbook-Second-Edition   Author: PacktPublishing   File: GUI.py    (license) View Source Project 6 votes vote down vote up
def getDateTime(self):
        fmtStrZone = "%Y-%m-%d %H:%M:%S %Z%z"
        # Get Coordinated Universal Time
        utc = datetime.now(timezone('UTC'))
        print(utc.strftime(fmtStrZone))
         
        # Convert UTC datetime object to Los Angeles TimeZone
        la = utc.astimezone(timezone('America/Los_Angeles'))
        print(la.strftime(fmtStrZone))
 
        # Convert UTC datetime object to New York TimeZone
        ny = utc.astimezone(timezone('America/New_York'))
        print(ny.strftime(fmtStrZone))

        # update GUI label with local Time and Zone       
#         self.lbl2.set(la.strftime(fmtStrZone))
                 
        # update GUI label with NY Time and Zone       
        self.lbl2.set(ny.strftime(fmtStrZone))

    
          
    ##################################################################################### 
Example 24
Project: chatbot_ner   Author: hellohaptik   File: date_detection.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, entity_name, timezone='UTC'):
        """
        Initializes the DateDetector object with given entity_name and pytz timezone object

        Args:
            entity_name (str): A string by which the detected date entity substrings would be replaced with on calling
                               detect_entity()
            timezone (Optional, str): timezone identifier string that is used to create a pytz timezone object
                                      default is UTC
        """
        self.text = ''
        self.tagged_text = ''
        self.processed_text = ''
        self.date = []
        self.original_date_text = []
        self.entity_name = entity_name
        self.tag = '__' + entity_name + '__'
        self.date_detector_object = DateDetector(entity_name=entity_name, timezone=timezone)
        self.bot_message = None 
Example 25
Project: chatbot_ner   Author: hellohaptik   File: time_detection.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, entity_name, timezone=pytz.timezone('UTC')):
        """Initializes a TimeDetector object with given entity_name and pytz timezone object

        Args:
            entity_name: A string by which the detected time stamp substrings would be replaced with on calling
                        detect_entity()
            timezone: Optional, pytz.timezone object used for getting current time, default is pytz.timezone('UTC')

        """
        self.entity_name = entity_name
        self.text = ''
        self.tagged_text = ''
        self.processed_text = ''
        self.time = []
        self.original_time_text = []
        self.tag = '__' + entity_name + '__'
        self.timezone = timezone
        # TODO form_check is Haptik specific ?
        self.form_check = True 
Example 26
Project: PySIGNFe   Author: thiagopena   File: base.py    (license) View Source Project 6 votes vote down vote up
def set_fuso_horaro(self, novo_valor):
        if novo_valor in pytz.country_timezones['br']:
            self._fuso_horario = pytz.timezone(novo_valor)

        #
        # Nos valores abaixo, não entendi ainda até agora, mas para o resultado
        # correto é preciso usar GMT+ (mais), não (menos) como seria de se
        # esperar...
        #
        elif novo_valor == '-04:00' or novo_valor == '-0400':
            self._fuso_horario = pytz.timezone('Etc/GMT+4')
        elif novo_valor == '-03:00' or novo_valor == '-0300':
            self._fuso_horario = pytz.timezone('Etc/GMT+3')
        elif novo_valor == '-02:00' or novo_valor == '-0200':
            self._fuso_horario = pytz.timezone('Etc/GMT+2')
        elif novo_valor == '-01:00' or novo_valor == '-0100':
            self._fuso_horario = pytz.timezone('Etc/GMT+1') 
Example 27
Project: Godavaru   Author: Godavaru   File: main.py    (license) View Source Project 6 votes vote down vote up
def on_command_error(ctx, error):
    console = bot.get_channel(358776134243975169)
    errid = id_generator()
    if isinstance(error, commands.CommandNotFound):
        return
    global totalErrors
    totalErrors += 1
    await ctx.send(":x: I ran into an error! Please report this on the support guild with the error ID, which is **{1}**. ```py\n{0}```".format(str(error)[29:], errid))
    webhook.send(content="[`"+str(datetime.datetime.now(pytz.timezone('America/New_York')).strftime("%H:%M:%S"))+"`][`Godavaru`][:x:]\n"
                       +"[`CommandHandler`][`Error`]\n"
                       +"[`ErrorInformation`][`{}`]: {}\n".format(errid, str(error)[29:])
                       +"[`GuildInformation`]: {}\n".format(ctx.message.guild.name+" ("+str(ctx.message.guild.id)+") owned by "+str(ctx.message.guild.owner)+" ("+str(ctx.message.author.id)+")")
                       +"[`AuthorInformation`]: {} ({})\n".format(str(ctx.message.author), str(ctx.message.author.id))
                       +"[`MessageInformation`]: {} ({})\n".format(ctx.message.clean_content, str(ctx.message.id)))
    print("["+str(datetime.datetime.now(pytz.timezone('America/New_York')).strftime("%H:%M:%S"))+"][Godavaru]\n"
                       +"[CommandHandler][Error]\n"
                       +"[ErrorInformation]: {}\n".format(str(error)[29:])
                       +"[GuildInformation]: {}\n".format(ctx.message.guild.name+" ("+str(ctx.message.guild.id)+") owned by "+str(ctx.message.guild.owner)+" ("+str(ctx.message.author.id)+")")
                       +"[AuthorInformation]: {} ({})\n".format(str(ctx.message.author), str(ctx.message.author.id))
                       +"[MessageInformation]: {} ({})\n".format(ctx.message.clean_content, str(ctx.message.id)))


# help command 
Example 28
Project: Godavaru   Author: Godavaru   File: cog_utils.py    (license) View Source Project 6 votes vote down vote up
def _time(self, ctx):
        """Determine the current time in a timezone specified.
        The timezone is case sensitive as seen in [this list](https://pastebin.com/B5tLQdEY).

        **Usage:** `g_time <timezone>

        **Permission:** User"""
        umsg = ctx.message.content
        args = umsg.split(' ')
        if len(args) > 1:
            try:
                if args[1].startswith('GMT'):
                    if args[1].startswith('GMT+'):
                        t = args[1].replace('+', '-')
                    elif args[1].startswith('GMT-'):
                        t = args[1].replace('-', '+')
                    tz = pytz.timezone('Etc/'+t)
                else:
                    tz = pytz.timezone(args[1])
                await ctx.send("The time in **{0}** is {1}".format(args[1], datetime.datetime.now(tz).strftime("`%H:%M:%S` on `%d-%b-%Y`")))
            except pytz.UnknownTimeZoneError:
                await ctx.send('Couldn\'t find that timezone, make sure to use one from this list: <https://pastebin.com/B5tLQdEY>\nAlso remember that timezones are case sensitive.')
        else:
            await ctx.send(":x: Usage: `{}time <timezone>`".format(self.bot.command_prefix[0])) 
Example 29
Project: webapp2   Author: GoogleCloudPlatform   File: extras_i18n_test.py    (license) View Source Project 6 votes vote down vote up
def test_to_local_timezone(self):
        i18n.get_i18n().set_timezone('US/Eastern')

        format = '%Y-%m-%d %H:%M:%S %Z%z'

        # Test datetime with timezone set
        base = datetime.datetime(2002, 10, 27, 6, 0, 0, tzinfo=pytz.UTC)
        localtime = i18n.to_local_timezone(base)
        result = localtime.strftime(format)
        self.assertEqual(result, '2002-10-27 01:00:00 EST-0500')

        # Test naive datetime - no timezone set
        base = datetime.datetime(2002, 10, 27, 6, 0, 0)
        localtime = i18n.to_local_timezone(base)
        result = localtime.strftime(format)
        self.assertEqual(result, '2002-10-27 01:00:00 EST-0500') 
Example 30
Project: webapp2   Author: GoogleCloudPlatform   File: extras_i18n_test.py    (license) View Source Project 6 votes vote down vote up
def test_to_utc(self):
        i18n.get_i18n().set_timezone('US/Eastern')

        format = '%Y-%m-%d %H:%M:%S'

        # Test datetime with timezone set
        base = datetime.datetime(2002, 10, 27, 6, 0, 0, tzinfo=pytz.UTC)
        localtime = i18n.to_utc(base)
        result = localtime.strftime(format)

        self.assertEqual(result, '2002-10-27 06:00:00')

        # Test naive datetime - no timezone set
        base = datetime.datetime(2002, 10, 27, 6, 0, 0)
        localtime = i18n.to_utc(base)
        result = localtime.strftime(format)
        self.assertEqual(result, '2002-10-27 11:00:00') 
Example 31
Project: webapp2   Author: GoogleCloudPlatform   File: extras_i18n_test.py    (license) View Source Project 6 votes vote down vote up
def test_get_timezone_location(self):
        i18n.get_i18n().set_locale('de_DE')
        self.assertEqual(
            i18n.get_timezone_location(pytz.timezone('America/St_Johns')),
            u'Neufundland-Zeit'
        )
        i18n.get_i18n().set_locale('de_DE')
        self.assertEqual(
            i18n.get_timezone_location(pytz.timezone('America/Mexico_City')),
            u'Nordamerikanische Inlandzeit'
        )
        i18n.get_i18n().set_locale('de_DE')
        self.assertEqual(
            i18n.get_timezone_location(pytz.timezone('Europe/Berlin')),
            u'Mitteleurop\xe4ische Zeit'
        )

    # ==========================================================================
    # Number formatting
    # ========================================================================== 
Example 32
Project: socialhome   Author: jaywink   File: generic.py    (GNU Affero General Public License v3.0) View Source Project 5 votes vote down vote up
def is_dst(zonename):
    """Check if current time in a time zone is in dst.

    From: http://stackoverflow.com/a/19778845/1489738
    """
    tz = pytz.timezone(zonename)
    now = pytz.utc.localize(datetime.datetime.utcnow())
    return now.astimezone(tz).dst() != datetime.timedelta(0) 
Example 33
Project: socialhome   Author: jaywink   File: generic.py    (GNU Affero General Public License v3.0) View Source Project 5 votes vote down vote up
def safe_make_aware(value, timezone=None):
    """Safely call Django's make_aware to get aware datetime.

    Makes sure DST doesn't cause problems."""
    if not timezone:
        timezone = settings.TIME_ZONE
    return make_aware(value, is_dst=is_dst(timezone)) 
Example 34
Project: ELO-Darts   Author: pwgraham91   File: datetime_lib.py    (MIT License) View Source Project 5 votes vote down vote up
def convert_to_tz_from_utc(utc_time, tz):
    local_time = utc_time.replace(tzinfo=pytz.utc).astimezone(pytz.timezone(tz))
    return local_time 
Example 35
Project: sopel-modules   Author: phixion   File: forecast.py    (license) View Source Project 5 votes vote down vote up
def get_sun(tz, forecast):
    if 'sunriseTime' not in forecast:
        return ""
    sunrise = datetime.fromtimestamp(forecast['sunriseTime'], tz=timezone(tz)).strftime('%H:%M')
    sunset = datetime.fromtimestamp(forecast['sunsetTime'], tz=timezone(tz)).strftime('%H:%M')
    return ", \u2600 \u2191 " + sunrise + " \u2193 " + sunset 
Example 36
Project: zipline-chinese   Author: zhanghan1990   File: algorithm.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def get_datetime(self, tz=None):
        """
        Returns the simulation datetime.
        """
        dt = self.datetime
        assert dt.tzinfo == pytz.utc, "Algorithm should have a utc datetime"

        if tz is not None:
            # Convert to the given timezone passed as a string or tzinfo.
            if isinstance(tz, string_types):
                tz = pytz.timezone(tz)
            dt = dt.astimezone(tz)

        return dt  # datetime.datetime objects are immutable. 
Example 37
Project: zipline-chinese   Author: zhanghan1990   File: input_validation.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def ensure_timezone(func, argname, arg):
    """Argument preprocessor that converts the input into a tzinfo object.

    Usage
    -----
    >>> from zipline.utils.preprocess import preprocess
    >>> @preprocess(tz=ensure_timezone)
    ... def foo(tz):
    ...     return tz
    >>> foo('utc')
    <UTC>
    """
    if isinstance(arg, tzinfo):
        return arg
    if isinstance(arg, string_types):
        return timezone(arg)

    raise TypeError(
        "{func}() couldn't convert argument "
        "{argname}={arg!r} to a timezone.".format(
            func=_qualified_name(func),
            argname=argname,
            arg=arg,
        ),
    ) 
Example 38
Project: zipline-chinese   Author: zhanghan1990   File: events.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def ensure_utc(time, tz='UTC'):
    """
    Normalize a time. If the time is tz-naive, assume it is UTC.
    """
    if not time.tzinfo:
        time = time.replace(tzinfo=pytz.timezone(tz))
    return time.replace(tzinfo=pytz.utc) 
Example 39
Project: zipline-chinese   Author: zhanghan1990   File: test_preprocess.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def test_ensure_timezone(self):
        @preprocess(tz=ensure_timezone)
        def f(tz):
            return tz

        valid = {
            'utc',
            'EST',
            'US/Eastern',
        }
        invalid = {
            # unfortunatly, these are not actually timezones (yet)
            'ayy',
            'lmao',
        }

        # test coercing from string
        for tz in valid:
            self.assertEqual(f(tz), pytz.timezone(tz))

        # test pass through of tzinfo objects
        for tz in map(pytz.timezone, valid):
            self.assertEqual(f(tz), tz)

        # test invalid timezone strings
        for tz in invalid:
            self.assertRaises(pytz.UnknownTimeZoneError, f, tz) 
Example 40
Project: stregsystemet   Author: f-klubben   File: views.py    (license) View Source Project 5 votes vote down vote up
def ranks_for_year(request, year):
    if (year <= 1900 or year > 9999):
        return render(request, 'admin/stregsystem/report/error_ranksnotfound.html', locals())
    milk = [2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 18, 19, 20, 24, 25, 43, 44, 45, 1865]
    caffeine = [11, 12, 30, 34, 37, 1787, 1790, 1791, 1795, 1799, 1800, 1803, 1804, 1837, 1864]
    beer = [13, 14, 29, 42, 47, 54, 65, 66, 1773, 1776, 1777, 1779, 1780, 1783, 1793, 1794, 1807, 1808, 1809, 1820,
            1822, 1840, 1844, 1846, 1847, 1853, 1855, 1856, 1858, 1859]
    coffee = [32, 35, 36, 39]
    vitamin = [1850, 1851, 1852, 1863]

    FORMAT = '%d/%m/%Y kl. %H:%M'
    last_year = year - 1
    from_time = fjule_party(year - 1)
    to_time = fjule_party(year)
    kr_stat_list = sale_money_rank(from_time, to_time)
    beer_stat_list = sale_product_rank(beer, from_time, to_time)
    caffeine_stat_list = sale_product_rank(caffeine, from_time, to_time)
    milk_stat_list = sale_product_rank(milk, from_time, to_time)
    coffee_stat_list = sale_product_rank(coffee, from_time, to_time)
    vitamin_stat_list = sale_product_rank(vitamin, from_time, to_time)
    from_time_string = from_time.strftime(FORMAT)
    to_time_string = to_time.strftime(FORMAT)
    current_date = timezone.now()
    is_ongoing = current_date > from_time and current_date <= to_time
    return render(request, 'admin/stregsystem/report/ranks.html', locals())


# gives a list of member objects, with the additional field sale__count, with the number of sales which are in the parameter id 
Example 41
Project: stregsystemet   Author: f-klubben   File: views.py    (license) View Source Project 5 votes vote down vote up
def last_fjule_party_year():
    current_date = timezone.now()
    fjule_party_this_year = fjule_party(current_date.year)
    if current_date > fjule_party_this_year:
        return current_date.year
    return current_date.year - 1


# year of the next fjuleparty 
Example 42
Project: stregsystemet   Author: f-klubben   File: views.py    (license) View Source Project 5 votes vote down vote up
def fjule_party(year):
    first_december = timezone.datetime(
        year,
        12,
        1,
        22,
        tzinfo=pytz.timezone("Europe/Copenhagen")
    )
    days_to_add = (11 - first_december.weekday()) % 7
    return first_december + datetime.timedelta(days=days_to_add) 
Example 43
Project: stregsystemet   Author: f-klubben   File: views.py    (license) View Source Project 5 votes vote down vote up
def late(date):
    return timezone.datetime(date.year, date.month, date.day, 23, 59, 59) 
Example 44
Project: stregsystemet   Author: f-klubben   File: views.py    (license) View Source Project 5 votes vote down vote up
def first_of_month(date):
    return timezone.datetime(date.year, date.month, 1, 23, 59, 59) 
Example 45
Project: stregsystemet   Author: f-klubben   File: views.py    (license) View Source Project 5 votes vote down vote up
def daily(request):
    current_date = timezone.now().replace(hour=0, minute=0, second=0)
    latest_sales = (Sale.objects
                    .prefetch_related('product', 'member')
                    .order_by('-timestamp')[:7])
    top_today = (Product.objects
                 .filter(sale__timestamp__gt=current_date)
                 .annotate(Count('sale'))
                 .order_by('-sale__count')[:7])

    startTime_day = timezone.now() - datetime.timedelta(hours=24)
    revenue_day = (Sale.objects
                   .filter(timestamp__gt=startTime_day)
                   .aggregate(Sum("price"))
                   ["price__sum"]) or 0.0
    startTime_month = timezone.now() - datetime.timedelta(days=30)
    revenue_month = (Sale.objects
                     .filter(timestamp__gt=startTime_month)
                     .aggregate(Sum("price"))
                     ["price__sum"]) or 0.0
    top_month_category = (Category.objects
                          .filter(product__sale__timestamp__gt=startTime_month)
                          .annotate(sale=Count("product__sale"))
                          .order_by("-sale")[:7])

    return render(request, 'admin/stregsystem/report/daily.html', locals()) 
Example 46
Project: stregsystemet   Author: f-klubben   File: views.py    (license) View Source Project 5 votes vote down vote up
def sales_api(request):
    startTime_month = timezone.now() - datetime.timedelta(days=30)
    qs = (Sale.objects
          .filter(timestamp__gt=startTime_month)
          .annotate(day=TruncDay('timestamp'))
          .values('day')
          .annotate(c=Count('*'))
          .annotate(r=Sum('price'))
          )
    db_sales = {i["day"].date(): (i["c"], money(i["r"])) for i in qs}
    base = timezone.now().date()
    date_list = [base - datetime.timedelta(days=x) for x in range(0, 30)]

    sales_list = []
    revenue_list = []
    for date in date_list:
        if date in db_sales:
            sales, revenue = db_sales[date]
            sales_list.append(sales)
            revenue_list.append(revenue)
        else:
            sales_list.append(0)
            revenue_list.append(0)

    items = {
        "day": date_list,
        "sales": sales_list,
        "revenue": revenue_list,
    }
    return JsonResponse(items) 
Example 47
Project: jx-sqlite   Author: mozilla   File: pulse.py    (Mozilla Public License 2.0) View Source Project 5 votes vote down vote up
def send(self, topic, message):
        """Publishes a pulse message to the proper exchange."""

        if not message:
            Log.error("Expecting a message")

        message._prepare()

        if not self.connection:
            self.connect()

        producer = Producer(
            channel=self.connection,
            exchange=Exchange(self.settings.exchange, type='topic'),
            routing_key=topic
        )

        # The message is actually a simple envelope format with a payload and
        # some metadata.
        final_data = Data(
            payload=message.data,
            _meta=set_default({
                'exchange': self.settings.exchange,
                'routing_key': message.routing_key,
                'serializer': self.settings.serializer,
                'sent': time_to_string(datetime.datetime.now(timezone(self.settings.broker_timezone))),
                'count': self.count
            }, message.metadata)
        )

        producer.publish(jsons.scrub(final_data), serializer=self.settings.serializer)
        self.count += 1 
Example 48
Project: dustbunny   Author: Teamworksapp   File: strategies.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def datetimes_in_range(allow_naive=None, timezones=None, start_date=None, end_date=None, start_inclusive=True, end_inclusive=True):
    """Return a strategy for generating datetimes.

    allow_naive=True will cause the values to sometimes be naive.
    timezones is the set of permissible timezones. If set to an empty
    collection all timezones must be naive. If set to None all available
    timezones will be used.

    """
    if timezones is None:
        timezones = list(pytz.all_timezones)
        timezones.remove(u'UTC')
        timezones.insert(0, u'UTC')
    timezones = [
        tz if isinstance(tz, dt.tzinfo) else pytz.timezone(tz)
        for tz in timezones
    ]
    if allow_naive is None:
        allow_naive = not timezones
    if not (timezones or allow_naive):
        raise InvalidArgument(
            u'Cannot create non-naive datetimes with no timezones allowed'
        )
    return DatetimeStrategy(
        allow_naive=allow_naive, timezones=timezones,
        start_date=start_date,
        end_date=end_date,
        start_inclusive=start_inclusive,
        end_inclusive=end_inclusive
    ) 
Example 49
Project: typepy   Author: thombashi   File: test_type.py    (MIT License) View Source Project 5 votes vote down vote up
def test_normal_timezone(self, value, timezone, expected):
        result = typepy.type.DateTime(
            value, strict_level=StrictLevel.MIN, timezone=timezone).convert()

        assert result == timezone.localize(expected) 
Example 50
Project: typepy   Author: thombashi   File: _datetime.py    (MIT License) View Source Project 5 votes vote down vote up
def __init__(self, value, timezone=None):
        super(DateTimeConverter, self).__init__(value)

        self.__datetime = None
        self.__timezone = timezone