我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pytz.timezone()。
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)}, )
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)
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))
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, ), )
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), )
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)
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), ) )
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' )
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)
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
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)
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)
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)
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()
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'])
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
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
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
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) ]
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
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))
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
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))
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)) #####################################################################################
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
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
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')
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
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]))
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')
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')
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 # ==========================================================================
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)
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))
def convert_to_tz_from_utc(utc_time, tz): local_time = utc_time.replace(tzinfo=pytz.utc).astimezone(pytz.timezone(tz)) return local_time
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
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.
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)
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)
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
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
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)
def late(date): return timezone.datetime(date.year, date.month, date.day, 23, 59, 59)
def first_of_month(date): return timezone.datetime(date.year, date.month, 1, 23, 59, 59)
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())
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)
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
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 )
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)
def __init__(self, value, timezone=None): super(DateTimeConverter, self).__init__(value) self.__datetime = None self.__timezone = timezone