def principalLoggedinHandler(event): prefs = IPersonalProfile(event.principal, None) if prefs is not None: lastLoginTime = prefs.lastLoginTime if lastLoginTime is not None: dt = parseDatetimetz(str(datetime.datetime.now())) td = dt - prefs.lastLoginTime if td.days or td.seconds > 60: prefs.lastLoginTime = dt else: prefs.lastLoginTime = parseDatetimetz(str(datetime.datetime.now()))
def add_newsitem(self, entry): """ Add news item """ title = entry.get('title', '') title = title.replace(' ', ' ').strip() description = BeautifulSoup(entry.get('summary', '')) description = ''.join([e for e in description.recursiveChildGenerator() if isinstance(e, unicode)]).strip() ptool = getToolByName(self.context, 'portal_properties') sanitize = getattr(ptool, 'sanitize', None) if sanitize: title_sanitize = sanitize.getProperty('subject', []) for expr in title_sanitize: title = title.replace(expr, '') desc_sanitize = sanitize.getProperty('body', []) for expr in desc_sanitize: description = description.replace(expr, '') body = description utils = getUtility(IText) description = utils.truncate(description, 20, 200) if not (title and description): return None url = entry.get('link', '#').strip() updated = entry.get('updated', None) if not updated: updated = datetime.now(bucharest) else: try: updated = parseDatetimetz(updated) except SyntaxError: updated = parseDatetimetz(updated.replace(' ', 'T', 1)) except: updated = datetime.now(bucharest) # Skip news older than 30 days plone_ro = 'plone.ro' in url if not plone_ro: try: if updated < (datetime.now() - timedelta(10)): return None except TypeError: if updated < (datetime.now(bucharest) - timedelta(10)): return None except Exception, err: logger.exception(err)
def principalProfileModified(profile, event): profile.modified = parseDatetimetz(str(datetime.datetime.now())) configlet = getUtility(IProfilesCategory) if configlet.photoAsAvatar and profile.profileImage: image = copy(profile.profileImage) configlet = getUtility(IAvatarConfiglet) if (image.width > configlet.maxWidth or image.height > configlet.maxHeight): try: image.data = convert( image.data, 'image/jpeg', sourceMimetype = image.mimeType, width = configlet.maxWidth, height = configlet.maxHeight, quality=88) except ConverterException, err: log = logging.getLogger('zojax.personal.profile') log.log(logging.WARNING, str(err)) return else: profile.avatarImage = image else: profile.avatarImage = image profile.avatar = 0
def change_timezone(dt, timezone): # if we are a float, make the (rather dubious) assumption that we're # looking at a UTC timestamp if isinstance(dt, float) or isinstance(dt, int): dt = datetime.datetime.fromtimestamp(dt, pytz.utc) # check to make sure we're not a Zope DateTime object elif isinstance(dt, DateTime.DateTime): dt = dt.toZone('UTC') dt = datetime.datetime(dt._year, dt._month, dt._day, dt._hour, dt._minute, int(dt._nearsec), int((dt._second - dt._nearsec) * 1000000), tzinfo=pytz.utc) elif isinstance(dt, str) or isinstance(dt, unicode): # if we have the format Sat, 10 Mar 2007 22:47:20 +1300 (NZDT) # strip the (NZDT) bit before parsing, otherwise we break the parser dt = re.sub(' \(.*?\)', '', dt) dt = parseDatetimetz(dt) assert isinstance(dt, datetime.datetime), \ ("dt is not a datetime instance (is a %s), if a datetime "\ "instance was not "\ "passed in as dt, it has not been converted correctly" %\ dt) tz = pytz.timezone(timezone) return tz.normalize(dt.astimezone(tz))
def __get__(self, inst, klass): if inst is None: return self attribute = getattr(inst.context, self._get_name, _marker) if attribute is _marker: field = self._field.bind(inst) attribute = getattr(field, 'default', _marker) if attribute is _marker: raise AttributeError(self._field.__name__) elif isinstance(attribute, Pdata): attribute = str(attribute) elif callable(attribute): attribute = attribute() if self._field._type == str: return attribute if isinstance(attribute, str) and inst.encoding: return attribute.decode(inst.encoding) if isinstance(attribute, DateTime): return parseDatetimetz(attribute.ISO8601()) if isinstance(attribute, (tuple, list)): if inst.encoding: attribute = [ isinstance(v, str) and v.decode(inst.encoding) or v for v in attribute ] if self._field._type == list: return attribute if self._field._type == tuple: return tuple(attribute) return set(attribute) return attribute
def test_getInputValue(self, value=u"2004-03-26 12:58:59", check_value=parseDatetimetz("2004-03-26 12:58:59")): self._widget.request.form["field.foo"] = u"" self.assertRaises(WidgetInputError, self._widget.getInputValue) self._widget.request.form["field.foo"] = value self.assertEquals(self._widget.getInputValue(), check_value) self._widget.request.form["field.foo"] = u"abc" self.assertRaises(ConversionError, self._widget.getInputValue)
def __get__(self, inst, cls=None): if inst is None: return self attribute = getattr(inst.context, self._get_name, _marker) if attribute is _marker: field = self._field.bind(inst) attribute = getattr(field, 'default', _marker) if attribute is _marker: raise AttributeError(self._field.__name__) elif isinstance(attribute, Pdata): attribute = str(attribute) elif callable(attribute): attribute = attribute() if self._field._type == str: return attribute if isinstance(self._field, FileUpload): return attribute if isinstance(attribute, str) and inst.encoding: return attribute.decode(inst.encoding) if isinstance(attribute, DateTime): return parseDatetimetz(attribute.ISO8601()) if isinstance(attribute, (tuple, list)): if inst.encoding: attribute = [ isinstance(v, str) and v.decode(inst.encoding) or v for v in attribute ] if self._field._type == list: return attribute if self._field._type == tuple: return tuple(attribute) return set(attribute) return attribute
def __get__(self, inst, klass): if inst is None: return self data = inst._mapping.get(self.__name__, ()) if data: return parseDatetimetz(data[0]) else: return None
def test_getInputValue(self, value=u'2004-03-26 12:58:59', check_value=parseDatetimetz('2004-03-26 12:58:59')): self._widget.request.form['field.foo'] = u'' self.assertRaises(WidgetInputError, self._widget.getInputValue) self._widget.request.form['field.foo'] = value self.assertEquals(self._widget.getInputValue(), check_value) self._widget.request.form['field.foo'] = u'abc' self.assertRaises(ConversionError, self._widget.getInputValue)
def json_to_python(self, d): for key in d: if key in ['created','modified','effective']: d[key] = parseDatetimetz(d[key]) if isinstance(d[key],str): d[key] = unicode(d[key]) if type(d[key]) in [ListType,TupleType]: d[key] = map(unicode,d[key]) return d
def json_to_python(self, d): for key in d: if key in ['created', 'modified', 'effective']: d[key] = parseDatetimetz(d[key]) if isinstance(d[key], str): d[key] = unicode(d[key]) if type(d[key]) in [ListType, TupleType]: d[key] = map(unicode, d[key]) return d
def _toFieldValue(self, input): # TODO: Manually check if weekday is enabled -- the user could have # directly entered the date. if input == self._missing: return self.context.missing_value else: try: dt = parseDatetimetz(input) except (DateTimeError, ValueError, IndexError), v: return super(DatetimeBase, self)._toFieldValue(input) else:
def _toFieldValue(self, value): dates = [] for token in itertools.chain(*[line.split("\n") for line in value.split(",")]): token = token.strip() if not token: continue try: date = parseDatetimetz(token) dates.append(date.date()) except (DateTimeError, ValueError, IndexError), v: raise ConversionError(_("Invalid date: $value", mapping={"value": token}), v)
def _toFieldValue(self, input): if input == self._missing: return self.context.missing_value else: try: # TODO: Currently datetimes return in local (server) # time zone if no time zone information was given. # Maybe offset-naive datetimes should be returned in # this case? (DV) return parseDatetimetz(input) except (DateTimeError, ValueError, IndexError), v: raise ConversionError(_("Invalid datetime data"), v)
def _toFieldValue(self, input): if input == self._missing: return self.context.missing_value else: try: # TODO: Currently datetimes return in local (server) # time zone if no time zone information was given. # Maybe offset-naive datetimes should be returned in # this case? (DV) return parseDatetimetz(input) except (DateTimeError, ValueError, IndexError) as v: raise ConversionError(_("Invalid datetime data"), v)
def _handle_success(self, action, data): # normalize set and datetime for k, v in data.iteritems(): if isinstance(v, Set): data[k] = set(v) elif isinstance(v, datetime) and v.tzname() is None: data[k] = parseDatetimetz(str(v)) changes = self.applyChanges(data) if changes: self.status = self.successMessage else: self.status = self.noChangesMessage return changes
def _toFieldValue(self, value): dates = [] for token in itertools.chain( *[line.split("\n") for line in value.split(",")]): token = token.strip() if not token: continue try: date = parseDatetimetz(token) dates.append(date.date()) except (DateTimeError, ValueError, IndexError), v: raise ConversionError( _("Invalid date: $value", mapping={"value": token}), v)
def _handle_success(self, action, data): # normalize set and datetime for k, v in data.iteritems(): if isinstance(v, Set): data[k] = set(v) elif isinstance(v, datetime) and v.tzname() is None: data[k] = parseDatetimetz(str(v)) if form.applyChanges(self.context, self.form_fields, data, self.adapters): self.context.reindexObject() obj_type = translate(self.context.Type(), self.context) self.status = _(u'${obj_type} changed.', mapping={'obj_type': obj_type}) else: self.status = _(u'Nothing to change.')
def getDateForField(self, field, source): """Returns a datetime object for the specified field in source. Returns None if the field value cannot be converted to date. """ # look in input element first pattern = '<input .* name="form.%s".* value="(.*)".*>' % field m = re.search(pattern, source) if m is None: # look in a select element pattern = '<select .* name="form.%s".*>.*' '<option value="(.*)" selected>*.</select>' % field m = re.search(pattern, source, re.DOTALL) if m is None: return None return parseDatetimetz(m.group(1))
def parse_date(value): """Get date specified in unicode ISO format to Python datetime object Dates are always assumed to be stored in GMT timezone :param str value: unicode date to be parsed :return: datetime; the specified value, converted to datetime >>> from pyams_utils.date import parse_date >>> parse_date('2016-11-15T10:13:12+00:00') datetime.datetime(2016, 11, 15, 10, 13, 12, tzinfo=<StaticTzInfo 'GMT'>) >>> parse_date(None) is None True """ if value is not None: return gmtime(parseDatetimetz(value)) return None
def getDateForField(self, field, source): """Returns a datetime object for the specified field in source. Returns None if the field value cannot be converted to date. """ # look in input element first pattern = '<input .* name="form.%s".* value="(.*)".*>' % field m = re.search(pattern, source) if m is None: # look in a select element pattern = '<select .* name="form.%s".*>.*' \ '<option value="(.*)" selected>*.</select>' % field m = re.search(pattern, source, re.DOTALL) if m is None: return None return parseDatetimetz(m.group(1))
def testDates(self): self.__testQualified('Dates', [ (u'', u'1990-01-01'), (u'Created', u'1980-10-01T23:11:10-04:00'), (u'Modified', u'2002-10-01T12:09:22-04:00'), (u'Effective', u'2002-10-09T00:00:00-04:00'), (u'Expires', u'2002-10-16T00:00:00-04:00'), (u'xxx', u'2000-07-04'), (u'xxx', u'2001-12-31'), (u'foo \u1111', u'2001-12-31'), ]) from zope.datetime import parseDatetimetz dc = self.dc self.assertEqual(dc.created, parseDatetimetz('1980-10-01T23:11:10-04:00')) self.assertEqual(dc.modified, parseDatetimetz('2002-10-01T12:09:22-04:00')) self.assertEqual(dc.effective, parseDatetimetz('2002-10-09T00:00:00-04:00')) self.assertEqual(dc.expires, parseDatetimetz('2002-10-16T00:00:00-04:00')) self.assertEqual(dc.Date(), u'1990-01-01') self.assertEqual(dc.CreationDate(), u'1980-10-01T23:11:10-04:00') self.assertEqual(dc.ModificationDate(), u'2002-10-01T12:09:22-04:00') self.assertEqual(dc.EffectiveDate(), u'2002-10-09T00:00:00-04:00') self.assertEqual(dc.ExpirationDate(), u'2002-10-16T00:00:00-04:00') dt = parseDatetimetz('2002-10-03T14:51:55-04:00') dc.modified = dt self.assertRaises(Exception, setattr, dc, 'modified', 'foo') modified = [qv[1] for qv in dc.getQualifiedDates() if qv[0] == u'Modified'] self.assertFalse(len(modified) != 1, "should be only one: %r" % modified) self.assertEqual(parseDatetimetz(modified[0]), dt) modified = dc.ModificationDate() self.assertEqual(parseDatetimetz(modified), dt)
def __call__(self): if os.path.exists('+maintenancetime.txt'): message = file('+maintenancetime.txt').read() try: maintenancetime = parseDatetimetz(message) except DateTimeError: # XXX SteveAlexander 2005-09-22: log a warning here. return '' timeleft = maintenancetime - utc_now() if timeleft > self.toomuchtime: return '' elif timeleft < self.notmuchtime: self.timelefttext = 'very very soon' else: self.timelefttext = 'in %s' % ( DurationFormatterAPI(timeleft).approximateduration()) return self.index() return ''
def __call__(self, nextURL): profile = IPersonalProfile(self.principal) if not profile.isComplete() and checkPermission('zojax.PersonalSpace', getSite()): if profile.firstname and profile.lastname: profile.modified = parseDatetimetz(str(datetime.datetime.now())) space = profile.space if space is not None: self.request.response.redirect( u'%s/profile/profile/'%absoluteURL(space, self.request)) IStatusMessage(self.request).add( _('You successfully logged in to portal. Please complete your profile.')) return True return False
def testDates(self): self.__testQualified('Dates', [ (u'', u'1990-01-01'), (u'Created', u'1980-10-01T23:11:10-04:00'), (u'Modified', u'2002-10-01T12:09:22-04:00'), (u'Effective', u'2002-10-09T00:00:00-04:00'), (u'Expires', u'2002-10-16T00:00:00-04:00'), (u'xxx', u'2000-07-04'), (u'xxx', u'2001-12-31'), (u'foo \u1111', u'2001-12-31'), ]) from zope.datetime import parseDatetimetz dc = self.dc self.assertEqual(dc.created, parseDatetimetz('1980-10-01T23:11:10-04:00')) self.assertEqual(dc.modified, parseDatetimetz('2002-10-01T12:09:22-04:00')) self.assertEqual(dc.effective, parseDatetimetz('2002-10-09T00:00:00-04:00')) self.assertEqual(dc.expires, parseDatetimetz('2002-10-16T00:00:00-04:00')) self.assertEqual(dc.Date(), u'1990-01-01') self.assertEqual(dc.CreationDate(), u'1980-10-01T23:11:10-04:00') self.assertEqual(dc.ModificationDate(), u'2002-10-01T12:09:22-04:00') self.assertEqual(dc.EffectiveDate(), u'2002-10-09T00:00:00-04:00') self.assertEqual(dc.ExpirationDate(), u'2002-10-16T00:00:00-04:00') dt = parseDatetimetz('2002-10-03T14:51:55-04:00') dc.modified = dt self.assertRaises(Exception, setattr, dc, 'modified', 'foo') modified = [qv[1] for qv in dc.getQualifiedDates() if qv[0] == u'Modified'] self.failIf(len(modified) != 1, "should be only one: %r" % modified) self.assertEqual(parseDatetimetz(modified[0]), dt) modified = dc.ModificationDate() self.assertEqual(parseDatetimetz(modified), dt)
def testDates(self): self.__testQualified( "Dates", [ (u"", u"1990-01-01"), (u"Created", u"1980-10-01T23:11:10-04:00"), (u"Modified", u"2002-10-01T12:09:22-04:00"), (u"Effective", u"2002-10-09T00:00:00-04:00"), (u"Expires", u"2002-10-16T00:00:00-04:00"), (u"xxx", u"2000-07-04"), (u"xxx", u"2001-12-31"), (u"foo \u1111", u"2001-12-31"), ], ) from zope.datetime import parseDatetimetz dc = self.dc self.assertEqual(dc.created, parseDatetimetz("1980-10-01T23:11:10-04:00")) self.assertEqual(dc.modified, parseDatetimetz("2002-10-01T12:09:22-04:00")) self.assertEqual(dc.effective, parseDatetimetz("2002-10-09T00:00:00-04:00")) self.assertEqual(dc.expires, parseDatetimetz("2002-10-16T00:00:00-04:00")) self.assertEqual(dc.Date(), u"1990-01-01") self.assertEqual(dc.CreationDate(), u"1980-10-01T23:11:10-04:00") self.assertEqual(dc.ModificationDate(), u"2002-10-01T12:09:22-04:00") self.assertEqual(dc.EffectiveDate(), u"2002-10-09T00:00:00-04:00") self.assertEqual(dc.ExpirationDate(), u"2002-10-16T00:00:00-04:00") dt = parseDatetimetz("2002-10-03T14:51:55-04:00") dc.modified = dt self.assertRaises(Exception, setattr, dc, "modified", "foo") modified = [qv[1] for qv in dc.getQualifiedDates() if qv[0] == u"Modified"] self.failIf(len(modified) != 1, "should be only one: %r" % modified) self.assertEqual(parseDatetimetz(modified[0]), dt) modified = dc.ModificationDate() self.assertEqual(parseDatetimetz(modified), dt)
def joinPrincipal(self, principalId, approved=True, _td = timedelta(milliseconds=1)): if principalId not in self: member = Member() event.notify(ObjectCreatedEvent(member)) self[principalId] = member joined = parseDatetimetz(str(datetime.now())) while joined in self.joined: joined = joined + _td member.joined = joined self.joined[joined] = principalId if not approved: member.approved = False self.notapproved.insert(principalId) else: event.notify(MemberApprovedEvent(member)) event.notify(ObjectModifiedEvent(self.__parent__)) updatePermissions(self.__parent__)
def principalRegisteredHandler(event): prefs = IPersonalProfile(event.principal, None) if prefs is not None: prefs.registered = parseDatetimetz(str(datetime.datetime.now()))
def _zope2python_dt(self, zope_dt): if zope_dt is None: return None return parseDatetimetz(zope_dt.ISO8601())
def testParseDatetimetz(self): self.assertEqual(parseDatetimetz('1999-12-31T01:02:03.037-00:30'), datetime(1999, 12, 31, 1, 2, 3, 37000, tzinfo(-30))) self.assertEqual(parseDatetimetz('2003 6 4 00:00:00 ', local=False), datetime(2003, 6, 4))
uid = INameChooser(self.context).chooseName(title, None) try: newsitem = self.context[uid] except Exception, err: pass else: return newsitem add_page = getMultiAdapter((self.context, self.request), name=u'add_newsitem.html') updated = entry.get('updated', None) if not updated: updated = self.context.updated or datetime.now(bucharest) else: updated = parseDatetimetz(updated) query = { 'title': title, 'description': description, 'url': url, 'updated': updated, 'tags': [self.context.__name__] } logger.info('Add newsitem %s in %s', uid, absoluteURL( self.context, self.request)) try: newsitem = add_page.createAndAdd(query) except Exception, err: logger.exception(err)
def query(self, default=None): return parseDatetimetz(str(self.content.get('datetime'))).astimezone(pytz.utc)
def _parseOptionalDate(self, date_string): """Attempt to parse `date_string`, or return None if invalid.""" try: return zope_datetime.parseDatetimetz(date_string) except (ValueError, zope_datetime.DateTimeError): return None
def _parseOptionalDate(self, date_string): """Attempt to parse `date_string`, or return None if invalid.""" try: return zope_datetime.parseDatetimetz(date_string) except (ValueError, zope_datetime.DateTimeError) as exception: return None