def normalize_field(self, value): if isinstance(value, basestring): locale = settings.get_locale() date_str, time_str = value.split(' ') date = dates.parse_date(date_str, locale) time = dates.parse_time(time_str, locale) dtime = datetime.datetime(date.year, date.month, date.day, time.hour, time.minute, time.second) dtime = settings.get_timezone().localize(dtime) utc_dt = dates.UTC.normalize(dtime) return utc_dt.replace(tzinfo=None) return super(DateTimeField, self).normalize_field(value)
def statistics(self): c.locations = meta.Session.query(Region, func.count(User.id)).filter(LocationTag.region_id == Region.id).filter(User.location_id == LocationTag.id).group_by(Region).all() c.geo_locations = meta.Session.query(User.location_city, func.count(User.id)).group_by(User.location_city).order_by(desc(func.count(User.id))).all() # Getting last week date range locale = c.locale from_time_str = format_date(date.today() - timedelta(7), format="short", locale=locale) to_time_str = format_date(date.today() + timedelta(1), format="short", locale=locale) from_time = parse_date(from_time_str, locale=locale) to_time = parse_date(to_time_str, locale=locale) uploads_stmt = meta.Session.query( Event.author_id, func.count(Event.created).label('uploads_count'))\ .filter(Event.event_type == 'file_uploaded')\ .filter(Event.created < to_time)\ .filter(Event.created >= from_time)\ .group_by(Event.author_id).order_by(desc('uploads_count')).limit(10).subquery() c.active_users = meta.Session.query(User, uploads_stmt.c.uploads_count.label('uploads'))\ .join((uploads_stmt, uploads_stmt.c.author_id == User.id)).all() return render('/statistics.mako')
def _filter_tour_date(self, date_from, date_to): if date_from: self.query = self.query.filter( Tour.start_date >= parse_date( date_from, locale=get_locale_name() ) ) if date_to: self.query = self.query.filter( Tour.end_date <= parse_date( date_to, locale=get_locale_name() ) )
def _filter_updated_date(self, updated_from, updated_to): if updated_from: self.query = self.query.filter( self.__log_subquery.c.modifydt >= parse_date( updated_from, locale=get_locale_name() ) ) if updated_to: self.query = self.query.filter( self.__log_subquery.c.modifydt <= parse_date( updated_to, locale=get_locale_name() ) )
def clean(self, value): locale=get_current_language() if value != "": try: value = parse_date(value, locale=locale) except: raise forms.ValidationError(self.error_messages['invalid']) return super(DateField, self).clean(value)
def render(self, name, value, attrs=None): locale=get_current_language() if value is None: value = "" if value and isinstance(value, basestring): try: value = parse_date(value, locale=locale) except: pass if value is not "" and not isinstance(value, basestring): value = format_date(value, locale=locale) return super(DateWidget, self).render(name, value, attrs)
def extract(self): value, error = super(DateWidgetExtractor, self).extract() if value is not NO_VALUE: if value: try: locale = ILocale(self.request, default='en') value = parse_date(value, locale=str(locale)) return value, error except (ValueError, IndexError) as err: return None, 'Unknown date pattern' else: value = None return value, error
def deserialize(self, node, cstruct): if not cstruct: return null try: result = parse_date(cstruct, locale=get_locale_name()) except: raise Invalid( node, _( self.err_template, mapping={'val': cstruct} ) ) return result
def parse_date(self, string): """Parse a date from a string This function uses the date format for the locale as a hint to determine the order in which the date fields appear in the string. >>> Locale('en', 'US').parse_date('4/1/04') datetime.date(2004, 4, 1) >>> Locale('de', 'DE').parse_date('01.04.2004') datetime.date(2004, 4, 1) In: - ``string`` -- the string containing the date Return: - a ``datetime.datetime`` object """ return dates.parse_date(string, self)
def parse_date(self, string): """Parses a date from a string. This function uses the date format for the locale as a hint to determine the order in which the date fields appear in the string. Example:: >>> parse_date('4/1/04', locale='en_US') datetime.date(2004, 4, 1) >>> parse_date('01.04.2004', locale='de_DE') datetime.date(2004, 4, 1) :param string: The string containing the date. :returns: The parsed date object. """ return dates.parse_date(string, locale=self.locale)
def setValue(self, newValue, repaintIsNotNeeded=False): # First handle special case when the client side component have a # date string but value is null (e.g. unparsable date string typed # in by the user). No value changes should happen, but we need to # do some internal housekeeping. if newValue is None and not self._uiHasValidDateString: # Side-effects of setInternalValue clears possible previous # strings and flags about invalid input. self.setInternalValue(None) # Due to DateField's special implementation of isValid(), # datefields validity may change although the logical value # does not change. This is an issue for Form which expects that # validity of Fields cannot change unless actual value changes. # # So we check if this field is inside a form and the form has # registered this as a field. In this case we repaint the form. # Without this hacky solution the form might not be able to clean # validation errors etc. We could avoid this by firing an extra # value change event, but feels like at least as bad solution as # this. self.notifyFormOfValidityChange() self.requestRepaint() return if newValue is None or isinstance(newValue, datetime): super(DateField, self).setValue(newValue, repaintIsNotNeeded) else: try: app = self.getApplication() if app is not None: l = app.getLocale() # Try to parse the given string value to datetime currentTimeZone = self.getTimeZone() if currentTimeZone is not None: currentTimeZone # FIXME: parse according to timezone val = parse_date(str(newValue), locale=l) super(DateField, self).setValue(val, repaintIsNotNeeded) except ValueError: self._uiHasValidDateString = False raise ConversionException(self.getParseErrorMessage())
def parse_date(string, locale=None): """Parses a date from a string. This function uses the date format for the locale as a hint to determine the order in which the date fields appear in the string. .. code-block:: python >>> parse_date('4/1/04', locale='en_US') datetime.date(2004, 4, 1) >>> parse_date('01.04.2004', locale='de_DE') datetime.date(2004, 4, 1) :param string: The string containing the date. :param locale: A locale code. If not set, uses the currently loaded locale. :returns: The parsed date object. """ locale = locale or get_locale() return dates.parse_date(string, locale=locale)
def parselocal_date(txt, locale): """TODO :param txt: TODO :param locale: the current locale (e.g: en, en_us, it)""" if txt.isdigit() and len(txt) in (6, 8): # is a date without separators: 101207 result = {} format = dates.get_date_format(locale=locale).pattern.lower() year_idx = format.index('y') month_idx = format.index('m') if month_idx < 0: month_idx = format.index('l') day_idx = format.index('d') indexes = [(year_idx, 'Y'), (month_idx, 'M'), (day_idx, 'D')] indexes.sort() is8 = (len(txt) == 8) for i, k in indexes: w = 2 if k == 'Y': if is8: w = 4 result[k] = int(txt[:w]) else: year = int(txt[:w]) if year < 70: result[k] = 2000 + year else: result[k] = 1900 + year else: result[k] = int(txt[:w]) txt = txt[w:] return datetime.date(result['Y'], result['M'], result['D']) else: try: date = dates.parse_date(txt, locale) except: raise GnrException('Invalid date') return date
def parselocal_date(txt, locale): """add??? :param txt: add??? :param locale: add??? :returns: add??? """ if txt.isdigit() and len(txt) in (6, 8): # is a date without separators: 101207 result = {} format = dates.get_date_format(locale=locale).pattern.lower() year_idx = format.index('y') month_idx = format.index('m') if month_idx < 0: month_idx = format.index('l') day_idx = format.index('d') indexes = [(year_idx, 'Y'), (month_idx, 'M'), (day_idx, 'D')] indexes.sort() is8 = (len(txt) == 8) for i, k in indexes: w = 2 if k == 'Y': if is8: w = 4 result[k] = int(txt[:w]) else: year = int(txt[:w]) if year < 70: result[k] = 2000 + year else: result[k] = 1900 + year else: result[k] = int(txt[:w]) txt = txt[w:] return datetime.date(result['Y'], result['M'], result['D']) else: return dates.parse_date(txt, locale)
def validator(node, value): if value >= parse_date(request.params.get('date_to')): raise colander.Invalid(node, _(u"Invalid dates, please check"))
def test_parse_date(): assert dates.parse_date('4/1/04', locale='en_US') == date(2004, 4, 1) assert dates.parse_date('01.04.2004', locale='de_DE') == date(2004, 4, 1)
def normalize_field(self, value): if isinstance(value, basestring): return parse_date(value, locale=settings.get_locale()) return super(DateField, self).normalize_field(value)
def users(self): locale = c.locale c.from_time_str = request.params.get('from_time') if not c.from_time_str: c.from_time_str = format_date(datetime.date.today() - datetime.timedelta(7), format="short", locale=locale) c.to_time_str = request.params.get('to_time') if not c.to_time_str: c.to_time_str = format_date(datetime.date.today() + datetime.timedelta(1), format="short", locale=locale) from_time = parse_date(c.from_time_str, locale=locale) to_time = parse_date(c.to_time_str, locale=locale) pages_stmt = meta.Session.query( Event.author_id, func.count(Event.created).label('pages_count'))\ .filter(Event.event_type == 'page_created')\ .filter(Event.created < to_time)\ .filter(Event.created >= from_time)\ .group_by(Event.author_id).subquery() uploads_stmt = meta.Session.query( Event.author_id, func.count(Event.created).label('uploads_count'))\ .filter(Event.event_type == 'file_uploaded')\ .filter(Event.created < to_time)\ .filter(Event.created >= from_time)\ .group_by(Event.author_id).subquery() messages_stmt = meta.Session.query( Event.author_id, func.count(Event.created).label('messages_count'))\ .filter(Event.event_type == 'mailinglist_post_created')\ .filter(Event.created < to_time)\ .filter(Event.created >= from_time)\ .group_by(Event.author_id).subquery() downloads_stmt = meta.Session.query( FileDownload.user_id, func.count(FileDownload.file_id).label('downloads_count'), func.count(func.distinct(FileDownload.file_id)).label('unique_downloads_count'), func.sum(File.filesize).label('downloads_size'))\ .filter(FileDownload.download_time < to_time)\ .filter(FileDownload.download_time >= from_time)\ .filter(FileDownload.range_start==None)\ .filter(FileDownload.range_end==None)\ .outerjoin((File, File.id == FileDownload.file_id))\ .group_by(FileDownload.user_id).subquery() users = meta.Session.query(User, func.coalesce(downloads_stmt.c.downloads_count, 0).label('downloads'), func.coalesce(downloads_stmt.c.unique_downloads_count, 0).label('unique_downloads'), func.coalesce(downloads_stmt.c.downloads_size, 0).label('downloads_size'), func.coalesce(uploads_stmt.c.uploads_count, 0).label('uploads'), func.coalesce(messages_stmt.c.messages_count, 0).label('messages'), func.coalesce(pages_stmt.c.pages_count, 0).label('pages'))\ .outerjoin((downloads_stmt, downloads_stmt.c.user_id == User.id))\ .outerjoin((uploads_stmt, uploads_stmt.c.author_id == User.id))\ .outerjoin((messages_stmt, messages_stmt.c.author_id == User.id))\ .outerjoin((pages_stmt, pages_stmt.c.author_id == User.id)) order_by = request.params.get('order_by', 'id') if order_by == 'id': users = users.order_by(desc(User.id)) else: users = users.order_by(desc(order_by)) c.users = paginate.Page( users, page=int(request.params.get('page', 1)), item_count=users.count() or 0, items_per_page=100, order_by=order_by, from_time=c.from_time_str, to_time=c.to_time_str) return render('/admin/users.mako')
def parse_date(string): """Parse a date from a string. """ return dates.parse_date(string, locale=get_locale())
def parseDate(date): from babel.dates import parse_date return parse_date(date, locale=config.displayLanguage[:2])
def test_parse_date(): assert dates.parse_date('4/1/04', locale='en_US') == date(2004, 4, 1) assert dates.parse_date('01.04.2004', locale='de_DE') == date(2004, 4, 1) assert dates.parse_date('2004-04-01', locale='sv_SE', format='short') == date(2004, 4, 1)