本文整理汇总了Python中mx.DateTime.now函数的典型用法代码示例。如果您正苦于以下问题:Python now函数的具体用法?Python now怎么用?Python now使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了now函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: enforce_user_constraints
def enforce_user_constraints(db):
""" Check a number of business rules for our users. """
account = Factory.get("Account")(db)
const = Factory.get("Constants")()
for row in account.list(filter_expired=False):
# We check FA/VA only
if row["np_type"] not in (const.fedaccount_type,
const.virtaccount_type):
continue
account.clear()
account.find(row["entity_id"])
# Expiration is not set -> force it to default
if row["expire_date"] is None:
logger.warn("Account %s (id=%s) is missing expiration date.",
account.account_name,
account.entity_id)
account.expire_date = now() + account.DEFAULT_ACCOUNT_LIFETIME
account.write_db()
# Expiration is too far in the future -> force it to default
if row["expire_date"] - now() > account.DEFAULT_ACCOUNT_LIFETIME:
logger.warn("Account %s (id=%s) has expire date too far in the"
" future.", account.account_name, account.entity_id)
account.expire_date = now() + account.DEFAULT_ACCOUNT_LIFETIME
account.write_db()
开发者ID:unioslo,项目名称:cerebrum,代码行数:26,代码来源:reaper.py
示例2: default_get
def default_get(self, cr, uid, fields, context=None):
'''
Get the default values for the replenishment rule
'''
res = super(stock_warehouse_order_cycle, self).default_get(cr, uid, fields, context=context)
company_id = res.get('company_id')
warehouse_id = res.get('warehouse_id')
if not 'company_id' in res:
company_id = self.pool.get('res.company')._company_default_get(cr, uid, 'stock.warehouse.automatic.supply', context=context)
res.update({'company_id': company_id})
if not 'warehouse_id' in res:
warehouse_id = self.pool.get('stock.warehouse').search(cr, uid, [('company_id', '=', company_id)], context=context)[0]
res.update({'warehouse_id': warehouse_id})
if not 'location_id' in res:
location_id = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id, context=context).lot_stock_id.id
res.update({'location_id': location_id})
if not 'consumption_period_from' in res:
res.update({'consumption_period_from': (DateFrom(now()) + RelativeDate(day=1)).strftime('%Y-%m-%d')})
if not 'consumption_period_to' in res:
res.update({'consumption_period_to': (DateFrom(now()) + RelativeDate(months=1, day=1, days=-1)).strftime('%Y-%m-%d')})
return res
开发者ID:hectord,项目名称:unifield,代码行数:28,代码来源:procurement.py
示例3: storicizza
def storicizza(self, tipologia="Documento", id_pdc=None, id_doc=None):
if self.msg is None:
raise Exception, "Impossibile storicizzare una mail non inizializzata"
import Env
bt = Env.Azienda.BaseTab
adb = Env.adb
from mx.DateTime import now
s = adb.DbTable(bt.TABNAME_DOCSEMAIL, 'docsemail')
s.CreateNewRow()
s.datcoda = now()
s.datsend = now()
s.id_pdc = id_pdc
s.id_doc = id_doc
s.tipologia = tipologia
s.mittente = self.SendFrom
s.destinat = ', '.join(self.SendTo)
s.oggetto = self.Subject
s.testo = self.Message
stream = None
if self.Attachments:
try:
f = open(self.Attachments[0], 'rb')
stream = f.read()
f.close()
except:
pass
if stream:
s.documento = stream
if not s.Save():
raise Exception, repr(s.GetError())
开发者ID:ziomar,项目名称:X4GA,代码行数:30,代码来源:comsmtp.py
示例4: actionScheduleAlarm
def actionScheduleAlarm(self, cmsg, dbcom):
sms_dict = self.alarm.retrieveData(cmsg)
activity = ACTIVE
if sms_dict == NOTFOUND:
self.log.LOG(LOG_ERROR, "sms.actionScheduleAlarm()", "TAGs are missing in the requisition to schedule an alarm. Aborting schedule.")
return "NOTFOUND"
blow = self.shared.mountTime(sms_dict[DATA_BLOW])
if blow == INVALID:
return "INVALID"
elif blow < now() or blow == now():
activity = FAILED
ret = dbcom.registerSMS(sms_dict[DATA_ORG], sms_dict[DATA_EXT+"0"], sms_dict[DATA_BLOW], sms_dict[DATA_OPER], sms_dict[DATA_MSG], activity)
if ret == OK and activity == ACTIVE:
alarm_thread = Thread(target=self.alarm.launch, args=(blow,))
alarm_thread.start()
self.log.LOG(LOG_INFO, "sms", "New alarm thread has been started.")
return "OK"
elif ret == NOTFOUND:
return "NOTFOUND"
elif activity == FAILED:
return "INVALID"
else:
return "ERROR"
开发者ID:dendriel,项目名称:SENAS,代码行数:35,代码来源:Manager.py
示例5: test_classCreate
def test_classCreate(self):
if not supports('fromDatabase'):
return
class OldAutoTest(SQLObject):
_connection = getConnection()
class sqlmeta(sqlmeta):
idName = 'auto_id'
fromDatabase = True
john = OldAutoTest(firstName='john',
lastName='doe',
age=10,
created=now(),
wannahavefun=False,
longField='x'*1000)
jane = OldAutoTest(firstName='jane',
lastName='doe',
happy='N',
created=now(),
wannahavefun=True,
longField='x'*1000)
assert not john.wannahavefun
assert jane.wannahavefun
assert john.longField == 'x'*1000
assert jane.longField == 'x'*1000
del classregistry.registry(
OldAutoTest.sqlmeta.registry).classes['OldAutoTest']
开发者ID:bieschke,项目名称:nuffle,代码行数:26,代码来源:test_auto_old.py
示例6: _empty_inventory
def _empty_inventory(self, cr, uid, data, context):
"""empty a location"""
pool = pooler.get_pool(cr.dbname)
inventory_line_obj = pooler.get_pool(cr.dbname).get('stock.inventory.line')
location_obj = pooler.get_pool(cr.dbname).get('stock.location')
res = {}
res_location = {}
if data['id']:
# pylint: disable-msg=W0212
res = location_obj._product_get(cr, uid, data['id'], context = context)
res_location[data['id']] = res
product_ids = []
inventory_id = pool.get('stock.inventory').create(cr, uid, {'name': "INV:" + now().strftime('%Y-%m-%d %H:%M:%S'),
'date': now().strftime('%Y-%m-%d %H:%M:%S'),
})
for location in res_location.keys():
res = res_location[location]
for product_id in res.keys():
cr.execute('select prodlot_id, name as id from stock_report_prodlots where location_id = %s and product_id = %s and name > 0', (location, product_id))
prodlots = cr.fetchall()
for prodlot in prodlots:
prod = pool.get('product.template').browse(cr, uid, product_id)
amount = prodlot[1]
if(amount):
inventory_line = {'inventory_id':inventory_id, 'location_id':location, 'product_id':product_id, 'product_uom':prod.uom_id.id, 'product_qty':0, 'prodlot_id':prodlot[0]}
inventory_line_obj.create(cr, uid, inventory_line)
product_ids.append(product_id)
pool.get('stock.inventory').action_done(cr, uid, [inventory_id], context = context)
if len(product_ids) == 0:
raise wizard.except_wizard(_('Message !'), _('No product in this location.'))
return {}
开发者ID:kevin-garnett,项目名称:openerp-from-oneyoung,代码行数:33,代码来源:empty_inventory.py
示例7: action_no_picking
def action_no_picking(self, cr, uid, ids):
"""creates the final move for the production and a move by product in the bom from
product's procurement location or a child her to production location"""
for production in self.browse(cr, uid, ids):
original_product_lines = map(lambda x: x.id, production.product_lines)
self.pool.get('mrp.production.product.line').write(cr, uid, map(lambda x: x.id, production.product_lines), {'production_id': None})
production = self.browse(cr, uid, production.id)
#create empty picking, delete
super(mrp_production, self).action_confirm(cr, uid, ids)
self.pool.get('mrp.production.product.line').write(cr, uid, original_product_lines, {'production_id': production.id})
production = self.browse(cr, uid, production.id)
#final move
final_moves_ids = self.pool.get('stock.move').search(cr, uid, [('production_id', '=', production.id)])
res_final_id = final_moves_ids[0]
if production.product_lines:
notvalidprodlots = []
order_product_lines = self.pool.get('mrp.production.product.line').search(cr, uid, [('production_id', '=', production.id)], order="product_qty DESC")
for line in order_product_lines:
obj_line = self.pool.get('mrp.production.product.line').browse(cr, uid, line)
#search the default prodlot and the location of this prodlot
default_prodlot, prodlot_location, default_qty = self.pool.get('stock.production.lot').get_default_production_lot(cr, uid, obj_line.product_id.product_tmpl_id.property_stock_procurement.id,
obj_line.product_id.id, obj_line.product_qty, True, notvalidprodlots)
notvalidprodlots.append((default_prodlot, prodlot_location, default_qty))
if not prodlot_location:
prodlot_location = obj_line.product_id.product_tmpl_id.property_stock_procurement.id
#creates the move in stock_move for the product not procure from deafult location of prodlot to production location
production_move = self.pool.get('stock.move').create(cr, uid, vals={
'product_uom' : obj_line.product_uom.id,
'product_uos_qty' : obj_line.product_uos_qty,
'date' : now().strftime('%Y-%m-%d %H:%M:%S'),
'product_qty' : obj_line.product_qty,
'product_uos' : obj_line.product_uos,
'location_id' : prodlot_location,
'product_id' : obj_line.product_id.id,
'prodlot_id' : default_prodlot,
'name' : 'NoProc:' + str(obj_line.product_id.product_tmpl_id.property_stock_procurement.id) + str(production.product_lines.index(obj_line)) + 'TO' + now().strftime('%Y-%m-%d %H:%M:%S'),
'date_planned' : now().strftime('%Y-%m-%d %H:%M:%S'),
'state' : 'draft',
'move_dest_id': res_final_id,
'location_dest_id' : obj_line.product_id.product_tmpl_id.property_stock_production.id,
})
#searches the final move in production and insert a registry in mrp_production_move_ids
if res_final_id:
cr.execute('insert into mrp_production_move_ids (production_id, move_id) values (%s,%s)', (production.id, production_move))
self.write(cr, uid, [production.id], {'state':'confirmed'})
return True
开发者ID:kevin-garnett,项目名称:openerp-from-oneyoung,代码行数:52,代码来源:mrp_production.py
示例8: on_change_method
def on_change_method(self, cr, uid, ids, method):
'''
Unfill the consumption period if the method is FMC
'''
res = {}
if method and method == 'fmc':
res.update({'consumption_period_from': False, 'consumption_period_to': False})
elif method and method == 'amc':
res.update({'consumption_period_from': (now() + RelativeDate(day=1, months=-2)).strftime('%Y-%m-%d'),
'consumption_period_to': (now() + RelativeDate(day=1, months=1, days=-1)).strftime('%Y-%m-%d')})
return {'value': res}
开发者ID:hectord,项目名称:unifield,代码行数:13,代码来源:threshold_value.py
示例9: onchange_partner_id
def onchange_partner_id(self, cr, uid, ids, move_id, partner_id, account_id=None, debit=0, credit=0, date=False, journal=False):
val = {}
val['date_maturity'] = False
if not partner_id:
return {'value':val}
if not date:
date = now().strftime('%Y-%m-%d')
part = self.pool.get('res.partner').browse(cr, uid, partner_id)
if part.property_payment_term:
res = self.pool.get('account.payment.term').compute(cr, uid, part.property_payment_term.id, 100, date)
if res:
val['date_maturity'] = res[0][0]
if not account_id:
id1 = part.property_account_payable.id
id2 = part.property_account_receivable.id
if journal:
jt = self.pool.get('account.journal').browse(cr, uid, journal).type
if jt == 'sale':
val['account_id'] = self.pool.get('account.fiscal.position').map_account(cr, uid, part and part.property_account_position or False, id2)
elif jt == 'purchase':
val['account_id'] = self.pool.get('account.fiscal.position').map_account(cr, uid, part and part.property_account_position or False, id1)
if val.get('account_id', False):
d = self.onchange_account_id(cr, uid, ids, val['account_id'])
val.update(d['value'])
return {'value':val}
开发者ID:MarkNorgate,项目名称:addons-EAD,代码行数:29,代码来源:account_move_line.py
示例10: entity_is_fresh
def entity_is_fresh(self, person, account):
"""Check if a person or account is 'fresh', i.e. if the account or
person is newly created, or if the account has been restored lately.
This is to be able to avoid blocking new phone numbers from systems
where the account is just activated.
"""
delay = now() - getattr(cisconf, 'FRESH_DAYS', 10)
# Check for traits only set for 'fresh' accounts:
for tr in (self.co.trait_student_new, self.co.trait_sms_welcome):
trait = account.get_trait(tr)
if trait and trait['date'] > delay:
logger.debug('Fresh trait %r for account %r, '
'so considered fresh', tr, account.account_name)
return True
# Check if person has recently been created:
for row in self.db.get_log_events(types=(self.clconst.person_create),
any_entity=person.entity_id,
sdate=delay):
logger.debug("Person %r is fresh", person.entity_id)
return True
logger.debug("Person %r (account %r) is not fresh",
person.entity_id, account.entity_id)
return False
开发者ID:unioslo,项目名称:cerebrum,代码行数:26,代码来源:Individuation.py
示例11: update_trait
def update_trait(self):
""" Update the 'trait_user_notified' trait by:
1. Creating it, if it doesn't exist
2. Resetting it if the date attribute is more than
days_reset days old.
3. Incrementing the numval attribute.
"""
# Initial values for new trait
last_reset = now()
num_sent = 0
trait = self.ac.get_trait(self.co.trait_user_notified)
# Trait date exists, and is not older than days_reset old.
if trait and (last_reset - self.days_reset) < trait.get("date"):
last_reset = trait.get("date")
num_sent = trait.get("numval") or 0
# Else, reset trait
# Increment and write the updated trait values
num_sent += 1
self.ac.populate_trait(self.co.trait_user_notified, numval=num_sent, date=last_reset)
self.ac.write_db()
if self.dryrun:
self.logger.warn(
"Dryrun, not writing trait '%s' for user '%s" % (str(self.co.trait_user_notified), self.ac.account_name)
)
self.ac._db.rollback()
else:
self.ac._db.commit()
开发者ID:unioslo,项目名称:cerebrum,代码行数:31,代码来源:ldap_notifier.py
示例12: loadPAClass
def loadPAClass(self):
pa_query = """select fk_pupil, fk_subject from prearranged_classes
where (time_start <= '%s' and time_end >= '%s') and fk_tutor = %d
"""
date = now()
d = self.db.db.runQuery(pa_query, (date, date, int(self.avId)))
d.addCallback(self._loadPupilAndSubject)
开发者ID:mgaitan,项目名称:beppo,代码行数:7,代码来源:TutorAvatar.py
示例13: populate_fagmiljo
def populate_fagmiljo(person_id, fagmiljo):
"""Add a given fagmiljo string to the given person."""
logger.debug("Populating fagmiljo for person_id=%s", person_id)
pe.clear()
pe.find(person_id)
pe.populate_trait(code=co.trait_fagmiljo, date=now(), strval=fagmiljo)
pe.write_db()
开发者ID:unioslo,项目名称:cerebrum,代码行数:7,代码来源:import_SAP_utvalg.py
示例14: test_mxDateTime
def test_mxDateTime():
setupClass(DateTime2)
_now = now()
dt2 = DateTime2(col1=_now, col2=_now.pydate(),
col3=Time(_now.hour, _now.minute, _now.second))
assert isinstance(dt2.col1, col.DateTimeType)
assert dt2.col1.year == _now.year
assert dt2.col1.month == _now.month
assert dt2.col1.day == _now.day
assert dt2.col1.hour == _now.hour
assert dt2.col1.minute == _now.minute
assert dt2.col1.second == int(_now.second)
assert isinstance(dt2.col2, col.DateTimeType)
assert dt2.col2.year == _now.year
assert dt2.col2.month == _now.month
assert dt2.col2.day == _now.day
assert dt2.col2.hour == 0
assert dt2.col2.minute == 0
assert dt2.col2.second == 0
assert isinstance(dt2.col3, (col.DateTimeType, col.TimeType))
assert dt2.col3.hour == _now.hour
assert dt2.col3.minute == _now.minute
assert dt2.col3.second == int(_now.second)
开发者ID:sqlobject,项目名称:sqlobject,代码行数:26,代码来源:test_datetime.py
示例15: test_mxDateTime
def test_mxDateTime():
setupClass(DateTime2)
_now = now()
dt2 = DateTime2(col1=_now, col2=_now, col3=Time(_now.hour, _now.minute, _now.second))
assert isinstance(dt2.col1, col.DateTimeType)
assert dt2.col1.year == _now.year
assert dt2.col1.month == _now.month
assert dt2.col1.day == _now.day
assert dt2.col1.hour == _now.hour
assert dt2.col1.minute == _now.minute
assert dt2.col1.second == int(_now.second)
assert isinstance(dt2.col2, col.DateTimeType)
assert dt2.col2.year == _now.year
assert dt2.col2.month == _now.month
assert dt2.col2.day == _now.day
if getConnection().dbName == "sqlite":
assert dt2.col2.hour == _now.hour
assert dt2.col2.minute == _now.minute
assert dt2.col2.second == int(_now.second)
else:
assert dt2.col2.hour == 0
assert dt2.col2.minute == 0
assert dt2.col2.second == 0
assert isinstance(dt2.col3, (col.DateTimeType, col.TimeType))
assert dt2.col3.hour == _now.hour
assert dt2.col3.minute == _now.minute
assert dt2.col3.second == int(_now.second)
开发者ID:rowex105,项目名称:encyclopediaWeb,代码行数:30,代码来源:test_datetime.py
示例16: removeClient
def removeClient(self, perspective):
"""Quita al cliente de id clientId de la lista de clientes actuales.
"""
#si era tutor elimino su room
if perspective.perspective_whoami() == TUTOR:
self.removeRoom(perspective.avId)
else:
if perspective.viewing != None:
self.wbRooms[perspective.viewing].roomViewerExit(perspective.avId)
#si esperaba lo elimino de la cola
if perspective.waitingInQueue != None:
self.wbQueues.leaveQueue(perspective.waitingInQueue, perspective.avId)
#si estaba en "observacion"
if perspective.waitingInRoom != None:
self.wbRooms[perspective.waitingInRoom].roomPupilStopWaiting()
avTutor = self.wbClients[perspective.waitingInRoom]
avTutor.cleanWhiteBoard()
self.exitViewers(perspective.waitingInRoom)
self.manageNextPupil(perspective.waitingInRoom, self.sessions.pupilEnd)
if perspective.roomId != None:
self.wbRooms[perspective.roomId].roomPupilExit(perspective.avId)
discount = (now().minute - perspective.lastMinute) % 60
perspective.discountIA(discount)
avTutor = self.wbClients[perspective.roomId]
try:
self.notifyClient(perspective.roomId, "El alumno abandono")
avTutor.saveClassStatus()
avTutor.cleanWhiteBoard()
except (pb.DeadReferenceError):
pass
self.exitViewers(perspective.roomId)
self.manageNextPupil(perspective.roomId, self.sessions.pupilEnd)
del(self.wbClients[perspective.avId])
del(self.wbClientStatus[perspective.avId])
开发者ID:mgaitan,项目名称:beppo,代码行数:34,代码来源:WBServer.py
示例17: delete_stale_events
def delete_stale_events(cl_events, db):
"""Remove all events of type cl_events older than GRACE_PERIOD.
cl_events is an iterable listing change_log event types that we want
expunged. These events cannot require any state change in Cerebrum (other
than their own deletion). It is the caller's responsibility to check that
this is so.
"""
if not isinstance(cl_events, (list, tuple, set)):
cl_events = [cl_events, ]
clconst = Factory.get("CLConstants")()
typeset_request = ", ".join(str(clconst.ChangeType(x))
for x in cl_events)
logger.debug("Deleting stale requests: %s", typeset_request)
for event in db.get_log_events(types=cl_events):
tstamp = event["tstamp"]
timeout = cereconf.GRACE_PERIOD
try:
params = json.loads(event["change_params"])
if params['timeout'] is not None:
timeout = DateTimeDelta(params['timeout'])
logger.debug('Timeout set to %s for %s',
(now() + timeout).strftime('%Y-%m-%d'),
event['change_id'])
if timeout > cereconf.MAX_INVITE_PERIOD:
logger.warning('Too long timeout (%s) for for %s',
timeout.strftime('%Y-%m-%d'),
event['change_id'])
timeout = cereconf.MAX_INVITE_PERIOD
except KeyError:
pass
if now() - tstamp <= timeout:
continue
logger.debug("Deleting stale event %s (@%s) for entity %s (id=%s)",
str(clconst.ChangeType(event["change_type_id"])),
event["tstamp"].strftime("%Y-%m-%d"),
fetch_name(event["subject_entity"], db),
event["subject_entity"])
db.remove_log_event(event["change_id"])
db.commit()
logger.debug("Deleted all stale requests: %s", typeset_request)
开发者ID:unioslo,项目名称:cerebrum,代码行数:47,代码来源:reaper.py
示例18: __absolute_time
def __absolute_time(self, time_str):
if time_str[0] == "+":
# Relative time
time = round_datetime(now() + Parser.TimeDeltaFromString(time_str[1:]))
else:
time = Parser.DateTimeFromString(time_str)
return time
开发者ID:queba,项目名称:haizea,代码行数:8,代码来源:rpc_commands.py
示例19: __absolute_time
def __absolute_time(self, time_str):
if time_str[0] == "+":
# Relative time
time = round_datetime(now() + ISO.ParseTime(time_str[1:]))
else:
time = Parser.ParseDateTime(time_str)
return time
开发者ID:EbtehalTurkiAlotaibi,项目名称:Cognitive,代码行数:8,代码来源:rpc_commands.py
示例20: _opening
def _opening(self, query, roomList, kind):
day = now()
if kind == IACLASS:
day = DateTime(2005, 5, (1 + day.day_of_week) % 7 + 1, day.hour, day.minute)
day = day + RelativeDateTime(minute=day.minute+2)
d = self.db.db.runQuery(query, (day,))
d.addCallback(self._updateRooms, roomList)
d.addCallback(self._openRooms, roomList, kind)
开发者ID:mgaitan,项目名称:beppo,代码行数:9,代码来源:cronTasks.py
注:本文中的mx.DateTime.now函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论