def localize_timestamp(timestamp, user): try: user_timezone = dates.get_timezone(user.timezone) except LookupError: user_timezone = dates.get_timezone('Etc/UTC') try: user_locale = Locale(user.locale) except core.UnknownLocaleError: user_locale = Locale('en') # Do our best to find a valid locale try: user_locale.date_formats except IOError: # An IOError will be raised if locale's casing is incorrect, e.g. de_de vs. de_DE # Attempt to fix the locale, e.g. de_de -> de_DE try: user_locale = Locale(fix_locale(user.locale)) user_locale.date_formats except (core.UnknownLocaleError, IOError): user_locale = Locale('en') formatted_date = dates.format_date(timestamp, format='full', locale=user_locale) formatted_time = dates.format_time(timestamp, format='short', tzinfo=user_timezone, locale=user_locale) return u'{time} on {date}'.format(time=formatted_time, date=formatted_date)
def timezone(self): tz = self.config.get('timezone', 'UTC') try: return get_timezone(tz) except LookupError: return get_timezone('UTC')
def test_function_errors(self): """ Test function errors :return: void """ sentence_filler = SentenceFiller() data = [ ('nl_BE', 'This is an invalid function --plura l__option 1__option 2__--.', {}), ('bo', 'This is an invalid function --plu(ral__option 1__option 2__--.', {}), ('ar', 'This is an invalid function --plu-ral__option 1__option 2__--.', {}), ('nl_BE', 'This is an invalid function --plura*l__option 1__option 2__--.', {}), ('bo', 'This is an invalid function --plu2ral__option 1__option 2__--.', {}), ('ar', 'This is an invalid function --pl^ural__option 1__option 2__--.', {}), ] for locale_str, given, params in data: locale = Locale.parse(locale_str, sep='_') time_zone = get_timezone('Europe/Brussels') number = Number(locale) time_instance = Time(locale, time_zone) localization = Localization(locale, number, time_instance) with self.assert_raises_regexp(SentenceFillerError, 'Function ".*?" was not valid.'): sentence_filler.fill_in(localization, given, params=params) data = [ ('nl_BE', 'This is an invalid function --plurale__option 1__option 2__--.', {}), ('bo', 'This is an invalid function --plura__option 1__option 2__--.', {}), ('ar', 'This is an invalid function --plur_al__option 1__option 2__--.', {}), ] for locale_str, given, params in data: locale = Locale.parse(locale_str, sep='_') time_zone = get_timezone('Europe/Brussels') number = Number(locale) time_instance = Time(locale, time_zone) localization = Localization(locale, number, time_instance) with self.assert_raises_regexp( SentenceFillerError, 'Using non-existing function "\w+".'): sentence_filler.fill_in(localization, given, params=params)
def _date_formats(unix_timestamp: float, locale: str = "en", time_zone: str = "UTC") -> Dict[str, Any]: """ Calculate different date formats / types. Args: unix_timestamp (float): A timestamp in seconds since 1970. locale (str): Locale code of language to use. Defaults to 'en'. time_zone (str): Timezone database name (https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). Returns: dict: Different date formats. """ utc_revision_date = datetime.utcfromtimestamp(int(unix_timestamp)) loc_revision_date = utc_revision_date.replace( tzinfo=get_timezone("UTC")).astimezone(get_timezone(time_zone)) return { "date": format_date(loc_revision_date, format="long", locale=locale), "datetime": " ".join([ format_date(loc_revision_date, format="long", locale=locale), loc_revision_date.strftime("%H:%M:%S"), ]), "iso_date": loc_revision_date.strftime("%Y-%m-%d"), "iso_datetime": loc_revision_date.strftime("%Y-%m-%d %H:%M:%S"), "timeago": '<span class="timeago" datetime="%s" locale="%s"></span>' % (loc_revision_date.isoformat(), locale), }
def _format_html_time_tag(datetime, what_to_display): now = time_utcnow() date = None if datetime.date() == now.date(): date = "Today" elif datetime.date() == (now - timedelta(days=1)).date(): date = "Yesterday" if what_to_display == "date-only": exact = babel_format_date(datetime, format="dd MMM yyyy", locale=_get_user_locale()) content = date if date else exact elif what_to_display == "date-and-time": exact = babel_format_datetime( datetime, format="dd.MM.yyyy HH:mm:ss", tzinfo=get_timezone(), locale=_get_user_locale() ) if date: content = date + ", " + \ babel_format_datetime( datetime, format="HH:mm:ss", tzinfo=get_timezone(), locale=_get_user_locale() ) else: content = exact else: raise ValueError("what_to_display argument invalid") isoformat = datetime.isoformat() return Markup('<time datetime="{isoformat}" data-toggle="tooltip" data-placement="top" title="{exact}">{content}</time>'.format( isoformat=isoformat, exact=exact, content=content ))
def test_param_errors(self): """ Test param errors :return: void """ sentence_filler = SentenceFiller() data = [ ('nl_BE', 'Have an invalid parameter: {param}.', { 'param': { 'value': 1 } }), ('bo', 'Have another invalid parameter: {param}.', { 'param': (1, 2, 3) }), ] for locale_str, given, params in data: locale = Locale.parse(locale_str, sep='_') time_zone = get_timezone('Europe/Brussels') number = Number(locale) time_instance = Time(locale, time_zone) localization = Localization(locale, number, time_instance) with self.assert_raises_regexp( SentenceFillerError, 'Invalid param type .*? found for "\w+"'): sentence_filler.fill_in(localization, given, params=params) data = [ ('ar', 'Irreplaceable parameter: {param}.', { 'param_a': { 'value': 1 } }), ('bo', 'Have another irreplaceable parameter: {param}.', { 'param_b': (1, 2, 3) }), ] for locale_str, given, params in data: locale = Locale.parse(locale_str, sep='_') time_zone = get_timezone('Europe/Brussels') number = Number(locale) time_instance = Time(locale, time_zone) localization = Localization(locale, number, time_instance) with self.assert_raises_regexp( SentenceFillerError, 'Param "param" could not be replaced.'): sentence_filler.fill_in(localization, given, params=params)
def _changlog(env): results = [] repo_cache = {} def _get_repo(path: str): if not os.path.isdir(path): path = os.path.dirname(path) if path not in repo_cache: repo_cache[path] = Repo(path, search_parent_directories=True).git return repo_cache[path] for page in env.variables.navigation.pages: if not page.url: continue unix_timestamp = time.time() try: realpath = os.path.realpath(page.file.abs_src_path) repo = _get_repo(realpath) unix_timestamp = repo.log(realpath, n=1, date="short", format="%at") unix_timestamp = int(unix_timestamp) except Exception as e: print(e) pass results.append((unix_timestamp, page)) results = sorted(results, key=lambda x: x[0], reverse=True) posts_group_by_month = defaultdict(list) ordered_keys = [] for unix_timestamp, page in results[:50]: utc_revision_date = datetime.utcfromtimestamp(unix_timestamp) loc_revision_date = utc_revision_date.replace(tzinfo=get_timezone('UTC')) \ .astimezone(get_timezone('Asia/Shanghai')) month_as_key = loc_revision_date.strftime('%Y年%m月') ordered_keys.append(month_as_key) post_update_datetime = loc_revision_date.strftime('%Y-%m-%d %H:%M:%S') posts_group_by_month[month_as_key].append( ' + [%s] [%s](%s)' % (post_update_datetime, page.title, page.abs_url)) output = [] for key in ordered_keys: output.append("+ **" + key + "**") output.append("\n".join(posts_group_by_month[key])) return "\n".join(output)
def localize_timestamp(timestamp, user): try: user_timezone = dates.get_timezone(user.timezone) except LookupError: user_timezone = dates.get_timezone('Etc/UTC') try: user_locale = Locale(user.locale) except core.UnknownLocaleError: user_locale = 'en' formatted_date = dates.format_date(timestamp, format='full', locale=user_locale) formatted_time = dates.format_time(timestamp, format='short', tzinfo=user_timezone, locale=user_locale) return u'{time} on {date}'.format(time=formatted_time, date=formatted_date)
class IvyFileTable(Table): def sort_url(self, col_id, reverse=False): pass classes = ["table","align-items-center","table-flush"] file_name = Col('File Name') date_added = BetterDatetimeCol('Date', "medium", tzinfo=get_timezone('US/Eastern'), locale='en') sample_count = Col('Total Records')
def value_from_raw(self, raw): if raw.value is None: return raw.missing_value('Missing datetime') try: chunks = raw.value.split(' ') date_info = [int(bit) for bit in chunks[0].split('-')] time_info = [int(bit) for bit in chunks[1].split(':')] datetime_info = date_info + time_info result = datetime(*datetime_info) if len(chunks) > 2: try: tz = get_timezone(chunks[-1]) except LookupError: if len(chunks[-1]) > 5: chunks[-1] = chunks[-1][-5:] delta = int(chunks[-1][1:3]) * 60 + int(chunks[-1][3:]) if chunks[-1][0] == '-': delta *= -1 tz = FixedOffset(delta) return tz.localize(result) return result except Exception: return raw.bad_value('Bad date format')
def short_date_format(evt, locale=DEFAULT_LOCALE, user_tz: tzinfo = None) -> str: lo = Locale.parse(locale, sep='_') tz = get_timezone(evt.timezone) now = datetime.now() if evt.end: if evt.start.year != now.year or evt.end.year != evt.start.year: return format_interval(evt.start.date(), evt.end.date(), 'yMMMMd', tzinfo=tz, locale=lo) else: # Year can be skipped return format_interval(evt.start.date(), evt.end.date(), 'MMMd', tzinfo=tz, locale=lo) if evt.start.year != now.year: return format_skeleton('yMMMMd', evt.start, tzinfo=tz, locale=lo) else: # Year can be skipped return format_skeleton('MMMMd', evt.start, tzinfo=tz, locale=lo)
def server_to_utc(dt): """Converts the given datetime in the server's TZ to UTC. The given datetime **MUST** be naive but already contain the correct time in the server's TZ. """ server_tz = get_timezone(config.DEFAULT_TIMEZONE) return server_tz.localize(dt).astimezone(pytz.utc)
def test_format(): l10n = L10n() d = date(2007, 4, 1) dformat = "EEE, MMM d, ''yy" expected = "Sun, Apr 1, '07" assert l10n.format(d, dformat, locale="en") == expected dt = datetime(2007, 4, 1, 15, 30) dformat = "yyyyy.MMMM.dd GGG hh:mm a" expected = "02007.April.01 AD 03:30 PM" assert l10n.format(dt, dformat, locale="en") == expected dt = datetime(2007, 4, 1, 15, 30, tzinfo=UTC) eastern = get_timezone("US/Eastern") dformat = "H:mm Z" expected = "11:30 -0400" assert l10n.format(dt, dformat, tzinfo=eastern, locale="en_US") == expected t = time(15, 30) tformat = "hh 'o''clock' a" expected = "03 o'clock PM" assert l10n.format(t, tformat, locale="en") == expected delta = timedelta(days=6) assert l10n.format(delta, locale="en_US") == "1 week" assert l10n.format(delta, granularity="month", locale="en_US") == "1 month" assert l10n.format(1099, locale="en_US") == "1,099" assert l10n.format(1.2345, locale="en_US") == "1.234" assert l10n.format("test", locale="en") == "test" assert l10n.format(None, locale="en_US") == ""
def test_format_interval_in_tz(): t1 = TEST_DT.replace(tzinfo=UTC) t2 = t1 + datetime.timedelta(minutes=18) hki_tz = get_timezone("Europe/Helsinki") assert dates.format_interval( t1, t2, "Hmv", tzinfo=hki_tz, locale="fi") == "13.46\u201314.04 aikavyöhyke: Suomi"
def test_format(): l10n = L10n() d = date(2007, 4, 1) dformat = "EEE, MMM d, ''yy" expected = u"Sun, Apr 1, '07" assert l10n.format(d, dformat, locale='en') == expected dt = datetime(2007, 4, 1, 15, 30) dformat = "yyyyy.MMMM.dd GGG hh:mm a" expected = u'02007.April.01 AD 03:30 PM' assert l10n.format(dt, dformat, locale='en') == expected dt = datetime(2007, 4, 1, 15, 30, tzinfo=UTC) eastern = get_timezone('US/Eastern') dformat = 'H:mm Z' expected = u'11:30 -0400' assert l10n.format(dt, dformat, tzinfo=eastern, locale='en_US') == expected t = time(15, 30) tformat = "hh 'o''clock' a" expected = u"03 o'clock PM" assert l10n.format(t, tformat, locale='en') == expected delta = timedelta(days=6) assert l10n.format(delta, locale='en_US') == u'1 week' assert l10n.format(delta, granularity='month', locale='en_US') == u'1 month' assert l10n.format(1099, locale='en_US') == u'1,099' assert l10n.format(1.2345, locale='en_US') == u'1.234' assert l10n.format('test', locale='en') == 'test' assert l10n.format(None, locale='en_US') == ''
def format_time(t, format='short', locale=None, timezone=None, server_tz=False, as_unicode=False): """ Basically a wrapper around Babel's own format_time """ inject_unicode = True if format == 'code': format = 'HH:mm' inject_unicode = False if not locale: locale = get_current_locale() if not timezone and t.tzinfo: timezone = session.tzinfo elif server_tz: timezone = config.DEFAULT_TIMEZONE if isinstance(timezone, basestring): timezone = get_timezone(timezone) rv = _format_time(t, format=format, locale=locale, tzinfo=timezone) if as_unicode: return rv return inject_unicode_debug( rv, 2).encode('utf-8') if inject_unicode else rv.encode('utf-8')
def get_translated_dict(): from babel.dates import Locale, get_timezone, get_timezone_name translated_dict = {} locale = Locale.parse(frappe.local.lang, sep="-") # timezones for tz in get_all_timezones(): timezone_name = get_timezone_name(get_timezone(tz), locale=locale, width="short") if timezone_name: translated_dict[tz] = timezone_name + " - " + tz # country names && currencies for country, info in get_all().items(): country_name = locale.territories.get((info.get("code") or "").upper()) if country_name: translated_dict[country] = country_name currency = info.get("currency") currency_name = locale.currencies.get(currency) if currency_name: translated_dict[currency] = currency_name return translated_dict
def server_to_utc(dt): """Converts the given datetime in the server's TZ to UTC. The given datetime **MUST** be naive but already contain the correct time in the server's TZ. """ server_tz = get_timezone(Config.getInstance().getDefaultTimezone()) return server_tz.localize(dt).astimezone(pytz.utc)
def datetime_formatter(request, value, format='medium', tzname=None, locale_name=None): """DateTime formatter Short:: >> dt = datetime(2011, 2, 6, 10, 35, 45, 80, pytz.UTC) >> request.fmt.datetime(dt, 'short') '02/06/11 04:35 AM' Medium:: >> request.fmt.datetime(dt, 'medium') 'Feb 06, 2011 04:35 AM' Long:: >> request.fmt.datetime(dt, 'long') 'February 06, 2011 04:35 AM -0600' Full:: >> request.fmt.datetime(dt, 'full') 'Sunday, February 06, 2011 04:35:45 AM CST' """ if not isinstance(value, datetime): return value tzinfo = None if tzname: tzinfo = get_timezone(tzname) if not tzinfo: PTAH = ptah.get_settings(ptah.CFG_ID_PTAH, request.registry) tzinfo = get_timezone(PTAH['timezone']) if not locale_name: locale_name = request.locale_name return text_type(format_datetime(value, format, tzinfo, locale_name))
def getdatelocalized(value): if value: from datetime import datetime from babel.dates import format_datetime, get_timezone return format_datetime(value, tzinfo=get_timezone(TIMEZONE), locale=LOCALE, format="d 'de' MMMM 'em' HH':'mm") else: return u"-"
def event_to_utc(dt, event): """Converts a datetime of an event to UTC. :param dt: A naive :class:`datetime.datetime` object in UTC :param event: An :class:`.Conference` object from which to take the timezone """ timezone = DisplayTZ(conf=event).getDisplayTZ() return get_timezone(timezone).localize(dt).astimezone(pytz.utc)
def scheduled_dt(self): if self.schedule_type.data == 'absolute': dt = datetime.combine(self.absolute_date.data, self.absolute_time.data) return get_timezone(self.timezone).localize(dt).astimezone(pytz.utc) elif self.schedule_type.data == 'relative': return self.event.getStartDate() - self.relative_delta.data elif self.schedule_type.data == 'now': return now_utc()
class InvitationTable(Table): classes = ["table","align-items-center","table-flush"] def sort_url(self, col_id, reverse=False): pass date_sent = BetterDatetimeCol('Date Sent', "medium", tzinfo=get_timezone('US/Eastern'), locale='en') location = Col('Location') date = Col('Date') total_recipients = Col('# Recipients')
def display_datetime(dt): """Render UTC datetimes to Amsterdam local time.""" babel_datetime_format = "EEEE d MMMM HH:mm y" dutch_timezone = get_timezone("Europe/Amsterdam") return format_datetime(dt, babel_datetime_format, tzinfo=dutch_timezone, locale="nl")
def test_format_datetime_tzinfo(): l10n = L10n() dt = datetime(2007, 4, 1, 15, 30, tzinfo=UTC) eastern = get_timezone('US/Eastern') dformat = 'H:mm Z' expected = u'11:30 -0400' assert l10n.format_datetime(dt, dformat, tzinfo=eastern, locale='en_US') == expected
def test_format_datetime_tzinfo(): l10n = L10n() dt = datetime(2007, 4, 1, 15, 30, tzinfo=UTC) eastern = get_timezone("US/Eastern") dformat = "H:mm Z" expected = "11:30 -0400" assert l10n.format_datetime(dt, dformat, tzinfo=eastern, locale="en_US") == expected
def format_datetime(value, format='medium'): print(value) value = parse(str(value)) if format == 'full': format="EEEE, d. MMMM y 'at' HH:mm" elif format == 'medium': format="EE dd.MM.y HH:mm" return dates.format_datetime(value, format, tzinfo=dates.get_timezone('Asia/Vladivostok'))
def normalize_timezone(tzinfo): if not tzinfo: return if isinstance(tzinfo, datetime.tzinfo): return tzinfo try: return get_timezone(tzinfo) except LookupError: return
def __init__(self, settings, size): # Config self.api_key = settings["api_key"] self.city_id = settings["city_id"] self.units = settings["units"] self.lang = settings["locale"].split("_")[0] self.timezone = get_timezone(settings["timezone"]) self.size = size self.temperature_format = "{:.0f}°F" if self.units == "imperial" else "{:.0f}°C"
def __init__(self, date_format='E MMMM d YYYY, h:mm a', timezone=None, ): self.date_format = date_format if timezone is not None: self.tzinfo = get_timezone(timezone) else: self.tzinfo = LOCALTZ
def full_date_format(evt, locale=DEFAULT_LOCALE, user_tz: tzinfo = None) -> str: """ full_date_format formats the date/time of an event. There are several things to keep in mind: - Events always have a start, but not always a specified end. - They might be just a range of dates (whole_day). - Events are located in some timezone. - If the consumer is in a different timezone than the event, it should be converted. - If the event is a whole day event, timezone should not be converted as this would bring dates out of alignment. - They should be displayed in a localized, but concise fashion, without unnecessary repetition. """ lo = Locale.parse(locale, sep='_') tz = get_timezone(evt.timezone) if evt.end: if evt.whole_day: return format_interval(evt.start.date(), evt.end.date(), 'yMMMMd', tzinfo=tz, locale=lo) else: if evt.start.date() == evt.end.date(): fmt = lo.datetime_formats['medium'].replace("'", "") return with_timezone( fmt.format( format_interval(evt.start.time(), evt.end.time(), 'Hm', tzinfo=tz, locale=lo), format_skeleton('yMMMMd', evt.start, tzinfo=tz, locale=lo)), evt, lo, user_tz) return with_timezone( format_interval(evt.start, evt.end, skeleton='yMMMMd Hm', tzinfo=tz, locale=lo), evt, lo, user_tz) # Event has no end date if evt.whole_day: return format_skeleton('yMMMMd', evt.start, tzinfo=tz, locale=lo) else: fmt = lo.datetime_formats['medium'].replace("'", "") return with_timezone( fmt.format( format_skeleton('Hm', evt.start, tzinfo=tz, locale=lo), format_skeleton('yMMMMd', evt.start, tzinfo=tz, locale=lo)), evt, lo, user_tz)
def _process(self): reminders = EventReminder.find(event_id=self.event.id).order_by( EventReminder.scheduled_dt.desc()).all() tz = get_timezone(DisplayTZ(conf=self.event).getDisplayTZ()) return WPReminders.render_template('reminders.html', self.event, event=self.event, reminders=reminders, timezone=tz)
def datetime_formatter(request, value, format='medium', tzname=None, locale_name=None): """DateTime formatter Short:: >> dt = datetime(2011, 2, 6, 10, 35, 45, 80, pytz.UTC) >> request.fmt.datetime(dt, 'short') '02/06/11 04:35 AM' Medium:: >> request.fmt.datetime(dt, 'medium') 'Feb 06, 2011 04:35 AM' Long:: >> request.fmt.datetime(dt, 'long') 'February 06, 2011 04:35 AM -0600' Full:: >> request.fmt.datetime(dt, 'full') 'Sunday, February 06, 2011 04:35:45 AM CST' """ if not isinstance(value, datetime): return value tzinfo = None if tzname: tzinfo = get_timezone(tzname) if not tzinfo: settings = request.registry.settings tzinfo = get_timezone(settings['ptah.timezone']) if not locale_name: locale_name = request.locale_name return text_type(format_datetime(value, format, tzinfo, locale_name))
def format_date(date: datetime) -> str: day = format_datetime(date, "dd", locale='pt_Br') month = format_datetime(date, "MMMM", locale='pt_Br') hour = format_datetime(date, "HH:mm", tzinfo=get_timezone('America/Sao_Paulo'), locale='pt_Br') date = f'dia {day} de {month.title()}, Ã s {hour}h' return date
def get_cert_date(force_date, locale, timezone): """ Get pertinent date for display on cert """ locale = locale or settings.DEFAULT_LOCALE timezone = timezone or settings.TIMEZONE if force_date: date = datetime.strptime(force_date, '%Y-%m-%d') else: from_zone = get_timezone(settings.TIMEZONE) to_zone = get_timezone(timezone) date = get_today() date = date.replace(tzinfo=from_zone) date = date.astimezone(to_zone) date = date.date() date = format_date(date, 'long', locale=locale) date = unicode(date) return date
def _get_defaults(self): reminder = self.reminder if reminder.is_relative: defaults_kwargs = {"schedule_type": "relative", "relative_delta": reminder.event_start_delta} else: # Use the user's preferred event timezone tz = get_timezone(DisplayTZ(conf=self.event).getDisplayTZ()) dt = reminder.scheduled_dt.astimezone(tz) defaults_kwargs = {"schedule_type": "absolute", "absolute_date": dt.date(), "absolute_time": dt.time()} return FormDefaults(reminder, **defaults_kwargs)
def time_formatter(request, value, format='medium', tzname=None, locale_name=None): """Time formatters """ if not isinstance(value, datetime) and not isinstance(value, time): return value tzinfo = None if tzname: tzinfo = get_timezone(tzname) if not tzinfo: settings = request.registry.settings tzinfo = get_timezone(settings['ptah.timezone']) if not locale_name: locale_name = request.locale_name return text_type(format_time(value, format, tzinfo, locale_name))
def test_datetime_timezone_est(env, pad): field = make_field(env, 'datetime') with Context(pad=pad): # Known timezone name, EST rv = field.deserialize_value('2016-04-30 01:02:03 EST', pad=pad) assert isinstance(rv, datetime.datetime) assert rv.year == 2016 assert rv.month == 4 assert rv.day == 30 assert rv.hour == 1 assert rv.minute == 2 assert rv.second == 3 assert rv.tzinfo is get_timezone('EST')
def timezones_choices(): """Timezones values and their labels for current locale. :return: an iterable of `(code, label)`, code being a timezone code and label the timezone name in current locale. """ utcnow = pytz.utc.localize(datetime.utcnow()) locale = _get_locale() for tz in sorted(pytz.common_timezones): tz = get_timezone(tz) now = tz.normalize(utcnow.astimezone(tz)) label = "({}) {}".format(get_timezone_gmt(now, locale=locale), tz.zone) yield (tz, label) # get_timezone_name(tz, locale=locale))
def set_defaults(self, default_locale, default_timezone): """Set the default locale from the configuration as an instance of :class:`babel.core.Locale` and the default timezone as a `datetime.tzinfo`. """ self.default_locale = ( utils.normalize_locale(default_locale) or Locale(DEFAULT_LOCALE) ) self.default_timezone = ( utils.normalize_timezone(default_timezone) or get_timezone(DEFAULT_TIMEZONE) )
def test_datetime_timezone_location(env, pad): field = make_field(env, 'datetime') with Context(pad=pad): # Known location name, Asia/Seoul rv = field.deserialize_value('2016-04-30 01:02:03 Asia/Seoul', pad=pad) assert isinstance(rv, datetime.datetime) assert rv.year == 2016 assert rv.month == 4 assert rv.day == 30 assert rv.hour == 1 assert rv.minute == 2 assert rv.second == 3 tzinfos = get_timezone('Asia/Seoul')._tzinfos # pylint: disable=no-member assert rv.tzinfo in itervalues(tzinfos)
def format_time(t, format='short', locale=None, timezone=None, server_tz=False): """ Basically a wrapper around Babel's own format_time """ if not locale: locale = currentLocale() if not timezone and t.tzinfo: timezone = DisplayTZ().getDisplayTZ() elif server_tz: timezone = HelperMaKaCInfo.getMaKaCInfoInstance().getTimezone() if timezone: timezone = get_timezone(timezone) return _format_time(t, format=format, locale=locale, tzinfo=timezone).encode('utf-8')
def convert_timezones(): timezones = {} found = set() today = datetime.utcnow() for zone_name in sorted(pytz.all_timezones): tzinfo = dates.get_timezone(zone_name) if tzinfo is None: continue short_name = zone_name try: transition = dates.get_next_timezone_transition(tzinfo, today) except TypeError: continue if transition is None: key = tzinfo.tzname(today) has_dst = False name = dates.get_timezone_name(tzinfo) else: from_tz = transition.from_tz to_tz = transition.to_tz from_tzinfo = transition.from_tzinfo to_tzinfo = transition.to_tzinfo if transition.from_tzinfo.localize(today).dst(): dst_tz = from_tz std_tz = to_tz dst_tzinfo = from_tzinfo std_tzinfo = to_tzinfo else: dst_tz = to_tz std_tz = from_tz dst_tzinfo = to_tzinfo std_tzinfo = from_tzinfo key = '%s/%s' % (std_tz, dst_tz) name = dates.get_timezone_name(std_tzinfo, zone_variation='generic') if name in found: continue found.add(name) timezones[short_name] = { 'short': key, 'name': name } with open('timezones.json', 'w') as f: json.dump({'timezones': timezones}, f, indent=2)
def format_time(t, format='short', locale=None, timezone=None, server_tz=False): """ Basically a wrapper around Babel's own format_time """ if format == 'code': format = 'HH:mm' if not locale: locale = get_current_locale() if not timezone and t.tzinfo: timezone = DisplayTZ().getDisplayTZ() elif server_tz: timezone = Config.getInstance().getDefaultTimezone() if timezone: timezone = get_timezone(timezone) return _format_time(t, format=format, locale=locale, tzinfo=timezone).encode('utf-8')
def format_time(t, format='short', locale=None, timezone=None, server_tz=False): """ Basically a wrapper around Babel's own format_time """ inject_unicode = True if format == 'code': format = 'HH:mm' inject_unicode = False if not locale: locale = get_current_locale() if not timezone and t.tzinfo: timezone = session.tzinfo elif server_tz: timezone = config.DEFAULT_TIMEZONE if isinstance(timezone, basestring): timezone = get_timezone(timezone) rv = _format_time(t, format=format, locale=locale, tzinfo=timezone) return inject_unicode_debug(rv, 2).encode('utf-8') if inject_unicode else rv.encode('utf-8')
def get_translated_dict(): from babel.dates import get_timezone, get_timezone_name, Locale translated_dict = {} locale = Locale.parse(frappe.local.lang, sep="-") # timezones for tz in get_all_timezones(): timezone_name = get_timezone_name(get_timezone(tz), locale=locale, width='short') if timezone_name: translated_dict[tz] = timezone_name + ' - ' + tz # country names && currencies for country, info in get_all().items(): country_name = locale.territories.get((info.get("code") or "").upper()) if country_name: translated_dict[country] = country_name currency = info.get("currency") currency_name = locale.currencies.get(currency) if currency_name: translated_dict[currency] = currency_name return translated_dict
def _process(self): reminders = EventReminder.find(event_id=self.event.id).order_by(EventReminder.scheduled_dt.desc()).all() tz = get_timezone(DisplayTZ(conf=self.event).getDisplayTZ()) return WPReminders.render_template('reminders.html', self.event, event=self.event, reminders=reminders, timezone=tz)
def utc_to_server(dt): """Converts the given UTC datetime to the server's TZ.""" server_tz = get_timezone(config.DEFAULT_TIMEZONE) return dt.astimezone(server_tz)
def pretty_datetime(d): return format_datetime(d, format='yyyy-MM-dd HH:mm:ss zzz', tzinfo=get_timezone('Europe/Berlin'), locale='en')
def test_timezone_formats(self): dt = datetime(2016, 1, 13, 7, 8, 35) tz = dates.get_timezone('America/Los_Angeles') dt = tz.localize(dt) formatted_string = dates.format_datetime(dt, 'z', locale='en') self.assertEqual(u'PST', formatted_string) formatted_string = dates.format_datetime(dt, 'zz', locale='en') self.assertEqual(u'PST', formatted_string) formatted_string = dates.format_datetime(dt, 'zzz', locale='en') self.assertEqual(u'PST', formatted_string) formatted_string = dates.format_datetime(dt, 'zzzz', locale='en') self.assertEqual(u'Pacific Standard Time', formatted_string) formatted_string = dates.format_datetime(dt, 'Z', locale='en') self.assertEqual(u'-0800', formatted_string) formatted_string = dates.format_datetime(dt, 'ZZ', locale='en') self.assertEqual(u'-0800', formatted_string) formatted_string = dates.format_datetime(dt, 'ZZZ', locale='en') self.assertEqual(u'-0800', formatted_string) formatted_string = dates.format_datetime(dt, 'ZZZZ', locale='en') self.assertEqual(u'GMT-08:00', formatted_string) formatted_string = dates.format_datetime(dt, 'ZZZZZ', locale='en') self.assertEqual(u'-08:00', formatted_string) formatted_string = dates.format_datetime(dt, 'OOOO', locale='en') self.assertEqual(u'GMT-08:00', formatted_string) formatted_string = dates.format_datetime(dt, 'VV', locale='en') self.assertEqual(u'America/Los_Angeles', formatted_string) formatted_string = dates.format_datetime(dt, 'VVV', locale='en') self.assertEqual(u'Los Angeles', formatted_string) formatted_string = dates.format_datetime(dt, 'X', locale='en') self.assertEqual(u'-08', formatted_string) formatted_string = dates.format_datetime(dt, 'XX', locale='en') self.assertEqual(u'-0800', formatted_string) formatted_string = dates.format_datetime(dt, 'XXX', locale='en') self.assertEqual(u'-08:00', formatted_string) formatted_string = dates.format_datetime(dt, 'XXXX', locale='en') self.assertEqual(u'-0800', formatted_string) formatted_string = dates.format_datetime(dt, 'XXXXX', locale='en') self.assertEqual(u'-08:00', formatted_string) formatted_string = dates.format_datetime(dt, 'x', locale='en') self.assertEqual(u'-08', formatted_string) formatted_string = dates.format_datetime(dt, 'xx', locale='en') self.assertEqual(u'-0800', formatted_string) formatted_string = dates.format_datetime(dt, 'xxx', locale='en') self.assertEqual(u'-08:00', formatted_string) formatted_string = dates.format_datetime(dt, 'xxxx', locale='en') self.assertEqual(u'-0800', formatted_string) formatted_string = dates.format_datetime(dt, 'xxxxx', locale='en') self.assertEqual(u'-08:00', formatted_string) dt = datetime(2016, 1, 13, 7, 8, 35) tz = dates.get_timezone('UTC') dt = tz.localize(dt) formatted_string = dates.format_datetime(dt, 'Z', locale='en') self.assertEqual(u'+0000', formatted_string) formatted_string = dates.format_datetime(dt, 'ZZ', locale='en') self.assertEqual(u'+0000', formatted_string) formatted_string = dates.format_datetime(dt, 'ZZZ', locale='en') self.assertEqual(u'+0000', formatted_string) formatted_string = dates.format_datetime(dt, 'ZZZZ', locale='en') self.assertEqual(u'GMT+00:00', formatted_string) formatted_string = dates.format_datetime(dt, 'ZZZZZ', locale='en') self.assertEqual(u'Z', formatted_string) formatted_string = dates.format_datetime(dt, 'OOOO', locale='en') self.assertEqual(u'GMT+00:00', formatted_string) formatted_string = dates.format_datetime(dt, 'VV', locale='en') self.assertEqual(u'Etc/UTC', formatted_string) formatted_string = dates.format_datetime(dt, 'VVV', locale='en') self.assertEqual(u'UTC', formatted_string) formatted_string = dates.format_datetime(dt, 'X', locale='en') self.assertEqual(u'Z', formatted_string) formatted_string = dates.format_datetime(dt, 'XX', locale='en') self.assertEqual(u'Z', formatted_string) formatted_string = dates.format_datetime(dt, 'XXX', locale='en') self.assertEqual(u'Z', formatted_string) formatted_string = dates.format_datetime(dt, 'XXXX', locale='en') self.assertEqual(u'Z', formatted_string) formatted_string = dates.format_datetime(dt, 'XXXXX', locale='en') self.assertEqual(u'Z', formatted_string) formatted_string = dates.format_datetime(dt, 'x', locale='en') self.assertEqual(u'+00', formatted_string) formatted_string = dates.format_datetime(dt, 'xx', locale='en') self.assertEqual(u'+0000', formatted_string) formatted_string = dates.format_datetime(dt, 'xxx', locale='en') self.assertEqual(u'+00:00', formatted_string) formatted_string = dates.format_datetime(dt, 'xxxx', locale='en') self.assertEqual(u'+0000', formatted_string) formatted_string = dates.format_datetime(dt, 'xxxxx', locale='en') self.assertEqual(u'+00:00', formatted_string) dt = datetime(2016, 1, 13, 7, 8, 35) tz = dates.get_timezone('Asia/Kolkata') dt = tz.localize(dt) formatted_string = dates.format_datetime(dt, 'zzzz', locale='en') self.assertEqual(u'India Standard Time', formatted_string) formatted_string = dates.format_datetime(dt, 'ZZZZ', locale='en') self.assertEqual(u'GMT+05:30', formatted_string) formatted_string = dates.format_datetime(dt, 'ZZZZZ', locale='en') self.assertEqual(u'+05:30', formatted_string) formatted_string = dates.format_datetime(dt, 'OOOO', locale='en') self.assertEqual(u'GMT+05:30', formatted_string) formatted_string = dates.format_datetime(dt, 'VV', locale='en') self.assertEqual(u'Asia/Calcutta', formatted_string) formatted_string = dates.format_datetime(dt, 'VVV', locale='en') self.assertEqual(u'Kolkata', formatted_string) formatted_string = dates.format_datetime(dt, 'X', locale='en') self.assertEqual(u'+0530', formatted_string) formatted_string = dates.format_datetime(dt, 'XX', locale='en') self.assertEqual(u'+0530', formatted_string) formatted_string = dates.format_datetime(dt, 'XXX', locale='en') self.assertEqual(u'+05:30', formatted_string) formatted_string = dates.format_datetime(dt, 'XXXX', locale='en') self.assertEqual(u'+0530', formatted_string) formatted_string = dates.format_datetime(dt, 'XXXXX', locale='en') self.assertEqual(u'+05:30', formatted_string) formatted_string = dates.format_datetime(dt, 'x', locale='en') self.assertEqual(u'+0530', formatted_string) formatted_string = dates.format_datetime(dt, 'xx', locale='en') self.assertEqual(u'+0530', formatted_string) formatted_string = dates.format_datetime(dt, 'xxx', locale='en') self.assertEqual(u'+05:30', formatted_string) formatted_string = dates.format_datetime(dt, 'xxxx', locale='en') self.assertEqual(u'+0530', formatted_string) formatted_string = dates.format_datetime(dt, 'xxxxx', locale='en') self.assertEqual(u'+05:30', formatted_string)