本文整理汇总了Python中mx.DateTime类的典型用法代码示例。如果您正苦于以下问题:Python DateTime类的具体用法?Python DateTime怎么用?Python DateTime使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DateTime类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: _dateConvertFromDB
def _dateConvertFromDB(d):
if d==None:
return None
for format in ('%Y-%m-%d', # Y/M/D
'%H:%M:%S', # hh:mm:ss
'%H:%M', # hh:mm
'%Y-%m'): # Y-M
try:
return DateTime.strptime(d, format)
except:
pass
dashind = max(d.rfind('-'), d.rfind('+'))
tz = d[dashind:]
d = d[:dashind]
#maybe it has a miliseconds ?
dotind = string.rfind(d, '.')
if dotind > 0:
d = d[:dotind]
try:
return DateTime.strptime(d, '%H:%M:%S'), tz # timetz
except:
pass
if 1:#try:
# why is tz returned above and not here?
return DateTime.strptime(d, '%Y-%m-%d %H:%M:%S') # full date
开发者ID:BackupTheBerlios,项目名称:skunkweb-svn,代码行数:27,代码来源:postconn.py
示例2: test_list_permission
def test_list_permission(self):
"""Testing permission listing."""
person_id = self.db_tools.create_person(self.person_ds().next())
account_id = self.db_tools.create_account(self.account_ds().next())
ou_id = self.db_tools.create_ou(
{'name': 'ephorte-test',
'acronym': 'ET',
'short_name': 'ePhorte-test',
'display_name': 'Test OU for ePhorte'})
self.assertFalse(self._ep.list_permission(),
'Listed permission, should be none')
self._ep.add_permission(
person_id, self._co.ephorte_perm_ar,
ou_id, account_id)
self._ep.add_permission(
person_id, self._co.ephorte_perm_ua,
ou_id, account_id)
self.assertEqual(
self._ep.list_permission(person_id),
[(person_id, self._co.ephorte_perm_ar, ou_id,
account_id, DateTime.today(), None),
(person_id, self._co.ephorte_perm_ua, ou_id,
account_id, DateTime.today(), None)],
'Failed listing added roles for person')
self.assertEqual(len(self._ep.list_permission()), 2,
'Number of permissions listed not equal')
开发者ID:unioslo,项目名称:cerebrum,代码行数:29,代码来源:test_ePhorte.py
示例3: _get_prod_stock_before
def _get_prod_stock_before(self, cr, uid, ids, name, arg, context={}):
res = {}
prod_obj = self.pool.get('product.product')
loc_ids = 11
for line in self.browse(cr, uid, ids, context=context):
# print 'fechaxxx: ',line.name
startf = datetime.datetime.fromtimestamp(time.mktime(
time.strptime(line.name, "%Y-%m-%d:%H:%M:%S")))
# print 'ffff: ',startf
start = DateTime(int(startf.year), 1, 1)
# end =
# DateTime(int(startf.year),int(startf.month),int(startf.day))
end = startf - datetime.timedelta(seconds=1)
d1 = start.strftime('%Y-%m-%d %H:%M:%S')
d2 = end.strftime('%Y-%m-%d %H:%M:%S')
# print 'd1xxxxxxx: ',d1
# print 'd2yyyyyyy: ',d2
c = context.copy()
c.update({'location': loc_ids, 'from_date': d1, 'to_date': d2})
res.setdefault(line.id, 0.0)
if line.product_id and line.product_id.id:
prd = prod_obj.browse(cr, uid, line.product_id.id, context=c)
res[line.id] = prd.qty_available
return res
开发者ID:meswapnilwagh,项目名称:odoo-adr,代码行数:25,代码来源:report_profit_picking.py
示例4: get_internal_seniority
def get_internal_seniority(self,cr,uid,ids,*args):
start_date = datetime.date.today()
end_date = datetime.date.today() # if the last contract has no en date, en date = today
internal_seniority = 0.0
internal_year_seniority = 0.0
internal_month_seniority = 0.0
# Get contracts for employee
contract_pool = self.pool.get('hr.contract')
contract_ids = contract_pool.search(cr,uid,[('employee_id','=',ids[0])],order='date_start desc') # contracts from today to first based on start date
contracts = contract_pool.browse(cr, uid, contract_ids)
# Get seniority for each contract
for contract in contracts:
seniority_rate = 1 # default seniority
start_date = DateTime.strptime(contract.date_start,'%Y-%m-%d')
if contract.seniority_rate:
seniority_rate = contract.seniority_rate
if contract.date_end:
end_date = DateTime.strptime(contract.date_end,'%Y-%m-%d')
internal_year_seniority += (end_date.year - start_date.year)*seniority_rate*1.0 # *1.0 to get a float
internal_month_seniority += (end_date.month - start_date.month + 1)*seniority_rate*1.0 # +1 : a started month is counted as a full month
end_date = start_date # if previous contract (in time scale) has no end date, its supposed end date is the current contract start date
# set seniority in years
internal_seniority = internal_year_seniority + internal_month_seniority/12 + internal_month_seniority//12
# Update internal seniority field
self.write(cr,uid,ids,{'internal_seniority':internal_seniority})
return True
开发者ID:kevin-garnett,项目名称:openerp-from-oneyoung,代码行数:26,代码来源:hr_contract_extension.py
示例5: Ymd
def Ymd(date=None):
if date is None:
return DateTime.today()
elif type(date) in (str, unicode):
return DateTime.strptime(date, '%Y-%m-%d')
elif type(date) in (type(DateTime.today()), datetime.datetime):
return date.strftime('%Y-%m-%d')
开发者ID:watcharapon,项目名称:exercises,代码行数:7,代码来源:wizard_obj1.py
示例6: test_reldat
def test_reldat(self):
# Picking values for relative datetime tests is difficult - the clock
# is running, and first-of-month (etc) change the result.
ds = self._get_reldate_ds()
self.assertRaises(ValueError, Filter.DatasetFilter, ds, 'test_filter',
'a >= reldate(days=-1, months=-1)')
self.assertRaises(TypeError, Filter.DatasetFilter, ds, 'test_filter',
'a >= reldate(poo=1)')
self.assertRaises(ValueError, Filter.DatasetFilter, ds, 'test_filter',
'a >= reldate(align="xxx")')
self._test(ds, 'a >= reldate(days=+1)', [0])
self._test(ds, 'a >= reldate()', [0, 1])
self._test(ds, 'a >= reldate(days=0)', [0, 1])
self._test(ds, 'a >= reldate(days=-1)', [0, 1, 2])
if DateTime.now().day_of_week == 0:
self._test(ds, 'a >= reldate(days=-7)', [0, 1, 2, 3, 4]) # this fails on Mondays!
else:
self._test(ds, 'a >= reldate(days=-7)', [0, 1, 2, 3]) # this fails on Mondays!
self._test(ds, 'a >= reldate(days=-7, align="monday")', [0, 1, 2, 3, 4])
if DateTime.now().day == 1:
expect = [0, 1, 2, 3, 4, 5, 6]
else:
expect = [0, 1, 2, 3, 4, 5]
self._test(ds, 'a >= reldate(months=-1)', expect)
self._test(ds, 'a >= reldate(months=-1, align="bom")', [0, 1, 2, 3, 4, 5, 6])
if DateTime.now().day == 1 and DateTime.now().month == DateTime.January:
expect = [0, 1, 2, 3, 4, 5, 6, 7, 8]
else:
expect = [0, 1, 2, 3, 4, 5, 6, 7]
self._test(ds, 'a >= reldate(years=-1)', expect)
self._test(ds, 'a >= reldate(years=-1, align="boy")', [0, 1, 2, 3, 4, 5, 6, 7, 8])
if DateTime.now().day_of_week == 0:
self._test(ds, 'a between(reldate(days=-7), reldate(days=-2))', [3, 4]) # also fails on Mondays
else:
self._test(ds, 'a between(reldate(days=-7), reldate(days=-2))', [3])
开发者ID:timchurches,项目名称:NetEpi-Analysis,代码行数:35,代码来源:filters.py
示例7: GetValue
def GetValue(self, manager, value, value_type = None):
retval = None
if manager == "ScanCoordinator":
if value == "receiver":
retval = "Rcvr1_2"
elif value == "nextScanNumber":
retval = "2"
elif value == "startTime,MJD":
gmt = DateTime.gmt()
loci = Loci()
mjd, _ = loci.DateTime2TimeStamp(gmt)
retval = str(mjd)
elif value == "startTime,seconds":
gmt = DateTime.gmt()
loci = Loci()
_, secs = loci.DateTime2TimeStamp(gmt)
retval = str(secs)
elif value == "projectId":
retval = 'TAPI_FRANK'
elif manager == "DCR":
if value.find("Channel,") == 0 or value.find("CH1_16,Tsys") == 0:
retval = "1"
elif manager == "Antenna":
if value == "azWrapMode":
retval = 'Auto'
elif manager == "Antenna,AntennaManager":
if value == "ccuData,Az,indicated":
retval = "180.0"
if retval is None:
retval = "%s's value" % value
self.Comment("GetValue(%s, %s) returning %s\n" % (manager,
value,
retval))
return retval
开发者ID:jmasters,项目名称:GbtTools,代码行数:34,代码来源:TPlotter.py
示例8: button_dummy
def button_dummy(self, cr, uid, ids, context):
for sheet in self.browse(cr, uid, ids, context):
if DateTime.strptime(sheet.date_current, "%Y-%m-%d") <= DateTime.strptime(sheet.date_from, "%Y-%m-%d"):
self.write(cr, uid, [sheet.id], {"date_current": sheet.date_from})
elif DateTime.strptime(sheet.date_current, "%Y-%m-%d") >= DateTime.strptime(sheet.date_to, "%Y-%m-%d"):
self.write(cr, uid, [sheet.id], {"date_current": sheet.date_to})
return True
开发者ID:MarkNorgate,项目名称:addons-EAD,代码行数:7,代码来源:hr_timesheet_sheet.py
示例9: _calc_dates
def _calc_dates(self, cr, uid, data, context):
res = {}
period_length = data["form"]["period_length"]
if period_length <= 0:
raise wizard.except_wizard(_("UserError"), _("You must enter a period length that cannot be 0 or below !"))
start = datetime.date.fromtimestamp(time.mktime(time.strptime(data["form"]["date1"], "%Y-%m-%d")))
start = DateTime(int(start.year), int(start.month), int(start.day))
if data["form"]["direction_selection"] == "past":
for i in range(5)[::-1]:
stop = start - RelativeDateTime(days=period_length)
res[str(i)] = {
"name": str((5 - (i + 1)) * period_length) + "-" + str((5 - i) * period_length),
"stop": start.strftime("%Y-%m-%d"),
"start": stop.strftime("%Y-%m-%d"),
}
start = stop - RelativeDateTime(days=1)
else:
for i in range(5):
stop = start + RelativeDateTime(days=period_length)
res[str(5 - (i + 1))] = {
"name": str((i) * period_length) + "-" + str((i + 1) * period_length),
"start": start.strftime("%Y-%m-%d"),
"stop": stop.strftime("%Y-%m-%d"),
}
start = stop + RelativeDateTime(days=1)
return res
开发者ID:MarkNorgate,项目名称:addons-EAD,代码行数:26,代码来源:wizard_aged_trial_balance.py
示例10: IsScriptValid
def IsScriptValid(self, script):
hasAccess = self.access
if hasAccess:
self.SetAccessToFunctionality(0)
self.output.AppendText("*** Begin Validation - %s ***\n" % str(DateTime.now()))
isValid, error = self.GetDocument().IsScriptValid(script, self.output)
if not isValid:
self.SetStatus(ILLICIT)
for e in error[-4:]:
self.output.AppendText(e + "\n")
else:
self.SetStatus(VALID)
if isValid:
self.output.AppendText("\nYour observing script is syntactically correct!\n\n")
self.output.AppendText("*** End Validation - %s ***\n" % str(DateTime.now()))
self.output.AppendText("\n\n")
if hasAccess:
self.SetAccessToFunctionality(1)
return isValid
开发者ID:jmasters,项目名称:GbtTools,代码行数:25,代码来源:EditPanel.py
示例11: __init__
def __init__(self, name, value, expires=None,
path=None, domain=None, secure=None):
""" Create a Netscape cookie for name with the given value.
If expires is given, the cookie will be a temporary cookie
which expires after a certain amount of time. expires may
be given as integer (seconds relative to the current
time), DateTime instance (absolute date/time) or
RelativeDateTime instance (relative date/time to current
time).
path, domain, secure work according to the Netscape
specification.
"""
self.name = name
self.value = value
if expires is not None:
# Long living cookie
if isinstance(expires, DateTime.DateTimeType):
self.expires = expires.gmtime()
elif isinstance(expires, DateTime.RelativeDateTime):
self.expires = DateTime.gmtime() + expires
else:
self.expires = DateTime.gmtime() + \
expires * DateTime.oneSecond
if path:
self.path = path
if domain:
self.domain = domain
if secure:
self.secure = 1
开发者ID:ourway,项目名称:Vixen,代码行数:33,代码来源:Cookie.py
示例12: create
def create(self, cr, uid, ids, datas, context={}):
io = StringIO.StringIO()
if 'date_start' not in datas:
cr.execute('select min(date_start) from project_task where id in %s', (tuple(ids),))
dt = cr.fetchone()[0]
if dt:
datas['date_start'] = dt[:10]
else:
datas['date_start'] = time.strftime('%Y-%m-%d')
if 'date_stop' not in datas:
cr.execute('select max(date_start),max(date_close) from project_task where id in %s', (tuple(ids),))
res = cr.fetchone()
datas['date_stop'] = (res[0] and res[0][:10]) or time.strftime('%Y-%m-%d')
if res[1] and datas['date_stop']<res[1]:
datas['date_stop'] = res[1][:10]
date_to_int = lambda x: int(x.ticks())
int_to_date = lambda x: '/a60{}'+DateTime.localtime(x).strftime('%d/%m/%Y')
datas = _burndown.compute_burndown(cr, uid, ids, datas['date_start'], datas['date_stop'])
canv = canvas.init(fname=io, format='pdf')
canv.set_author("Open ERP")
max_hour = reduce(lambda x,y: max(y[1],x), datas, 0)
date_to_int = lambda x: int(x.ticks())
int_to_date = lambda x: '/a60{}'+DateTime.localtime(x).strftime('%d %m %Y')
def _interval_get(*args):
result = set()
for i in range(20):
d = DateTime.localtime(datas[0][0] + (((datas[-1][0]-datas[0][0])/20)*(i+1)))
res = DateTime.DateTime(d.year, d.month, d.day).ticks()
result.add(res)
return list(result)
if datas[-1][0] == datas[0][0]:
x_range = (datas[0][0],datas[-1][0]+1)
else:
x_range = (datas[0][0],datas[-1][0])
ar = area.T(x_grid_style=line_style.gray50_dash1,
x_axis=axis.X(label="Date", format=int_to_date),
y_axis=axis.Y(label="Burndown Chart - Planned Hours"),
x_grid_interval=_interval_get,
x_range = x_range,
y_range = (0,max_hour),
legend = None,
size = (680,450))
ar.add_plot(line_plot.T(data=datas))
ar.draw(canv)
canv.close()
self.obj = external_pdf(io.getvalue())
self.obj.render()
return (self.obj.pdf,'pdf')
开发者ID:MarkNorgate,项目名称:addons-EAD,代码行数:59,代码来源:task_burndown.py
示例13: setTime
def setTime(self, target, from_or_till):
today = DateTime.today()
col = self._template.getColumn((target, from_or_till))
row = self.getRowForDate(today)
now = DateTime.now()
value = now.abstime / 60 / 60 / 24
print "+ %s %s: Setting time at (%s, %s) to %s" % (from_or_till, target, row, col, now)
self._xlSheet.setCell(row, col, value)
开发者ID:HarmonyEnterpriseSolutions,项目名称:toolib,代码行数:8,代码来源:businesstime.py
示例14: _project_compute
def _project_compute(cr, uid, project_id):
project = pooler.get_pool(cr.dbname).get('project.project').browse(cr, uid, project_id)
if project.date_start:
date_begin = DateTime.strptime(project.date_start, '%Y-%m-%d')
else:
date_begin = DateTime.now()
tasks, last_date = _compute_project(cr, uid, project, date_begin)
return tasks, last_date
开发者ID:MarkNorgate,项目名称:addons-EAD,代码行数:8,代码来源:_date_compute.py
示例15: __init__
def __init__(self, db, const, id=None):
self._db = db
self.co = const
midnight = DateTime.today()
now = DateTime.now()
# if we are past 22:00 this day, schedule for tomorrow evening
if (now - midnight) > DateTime.TimeDeltaFrom(hours=22):
self.batch_time = midnight + DateTime.TimeDeltaFrom(days=1,
hours=22)
# ... otherwise, schedule for this day
else:
self.batch_time = midnight + DateTime.TimeDeltaFrom(hours=22)
self.now = now
# "None" means _no_ conflicts, there can even be several of
# that op pending. All other ops implicitly conflict with
# themselves, so there can only be one of each op.
self.conflicts = {
int(const.bofh_move_user): [const.bofh_move_student,
const.bofh_move_user_now,
const.bofh_move_request,
const.bofh_delete_user],
int(const.bofh_move_student): [const.bofh_move_user,
const.bofh_move_user_now,
const.bofh_move_request,
const.bofh_delete_user],
int(const.bofh_move_user_now): [const.bofh_move_student,
const.bofh_move_user,
const.bofh_move_request,
const.bofh_delete_user],
int(const.bofh_move_request): [const.bofh_move_user,
const.bofh_move_user_now,
const.bofh_move_student,
const.bofh_delete_user],
int(const.bofh_move_give): None,
int(const.bofh_archive_user): [const.bofh_move_user,
const.bofh_move_user_now,
const.bofh_move_student,
const.bofh_delete_user],
int(const.bofh_delete_user): [const.bofh_move_user,
const.bofh_move_user_now,
const.bofh_move_student,
const.bofh_email_create],
int(const.bofh_email_create): [const.bofh_email_delete,
const.bofh_delete_user],
int(const.bofh_email_delete): [const.bofh_email_create],
int(const.bofh_email_convert): [const.bofh_email_delete],
int(const.bofh_sympa_create): [const.bofh_sympa_remove],
int(const.bofh_sympa_remove): [const.bofh_sympa_create],
int(const.bofh_quarantine_refresh): None,
int(const.bofh_email_restore): [const.bofh_email_create],
int(const.bofh_homedir_restore): [const.bofh_move_user,
const.bofh_move_user_now,
const.bofh_move_student,
const.bofh_delete_user]
}
开发者ID:unioslo,项目名称:cerebrum,代码行数:58,代码来源:utils.py
示例16: date_today
def date_today(self, cr, uid, ids, context):
for sheet in self.browse(cr, uid, ids, context):
if DateTime.now() <= DateTime.strptime(sheet.date_from, "%Y-%m-%d"):
self.write(cr, uid, [sheet.id], {"date_current": sheet.date_from})
elif DateTime.now() >= DateTime.strptime(sheet.date_to, "%Y-%m-%d"):
self.write(cr, uid, [sheet.id], {"date_current": sheet.date_to})
else:
self.write(cr, uid, [sheet.id], {"date_current": time.strftime("%Y-%m-%d")})
return True
开发者ID:MarkNorgate,项目名称:addons-EAD,代码行数:9,代码来源:hr_timesheet_sheet.py
示例17: _default_date_to
def _default_date_to(self, cr, uid, context={}):
user = self.pool.get("res.users").browse(cr, uid, uid, context)
r = user.company_id and user.company_id.timesheet_range or "month"
if r == "month":
return (DateTime.now() + DateTime.RelativeDateTime(months=+1, day=1, days=-1)).strftime("%Y-%m-%d")
elif r == "week":
return (DateTime.now() + DateTime.RelativeDateTime(weekday=(DateTime.Sunday, 0))).strftime("%Y-%m-%d")
elif r == "year":
return time.strftime("%Y-12-31")
return time.strftime("%Y-%m-%d")
开发者ID:MarkNorgate,项目名称:addons-EAD,代码行数:10,代码来源:hr_timesheet_sheet.py
示例18: test_get_quarantine
def test_get_quarantine(entity, initial_account, quar_x, quar_y):
entity.add_entity_quarantine(quar_x,
initial_account.entity_id,
start=dt.now() + 1)
quars = entity.get_entity_quarantine()
assert len(quars) == 1
quars = entity.get_entity_quarantine(qtype=quar_y)
assert len(quars) == 0
entity.add_entity_quarantine(quar_y,
initial_account.entity_id,
start=dt.now() - 1)
entity.disable_entity_quarantine(quar_y, dt.now() + 1)
quars = entity.get_entity_quarantine()
assert len(quars) == 2
quars = entity.get_entity_quarantine(qtype=quar_x)
assert len(quars) == 1
assert quars[0]['quarantine_type'] == quar_x
quars = entity.get_entity_quarantine(qtype=quar_x, only_active=True)
assert len(quars) == 0
quars = entity.get_entity_quarantine(qtype=quar_y,
filter_disable_until=True)
assert len(quars) == 0
开发者ID:unioslo,项目名称:cerebrum,代码行数:28,代码来源:test_EntityQuarantine.py
示例19: __verify_detect_packet
def __verify_detect_packet(self, packet):
lines = string.split(packet, cClinitek50.EOL)
# product ID: 6510 = Clinitek 50
tmp = lines[1][:4]
if tmp != cClinitek50.dev_id:
_log.Log(gmLog.lErr, 'device does not seem to be a Clinitek 50, product ID is [%s], expected [%s]' % (tmp, cClinitek50.dev_id))
_log.Log(gmLog.lData, lines)
return None
# product revision
tmp = lines[1][4:6]
if tmp not in cClinitek50.known_good_dev_revs:
_log.Log(gmLog.lWarn, 'product revision [%s] untested, trying to continue anyways' % tmp)
# software version
tmp = lines[1][6:11]
if tmp not in cClinitek50.known_good_sw_versions:
_log.Log(gmLog.lWarn, 'software version [%s] untested, trying to continue anyways' % tmp)
# date/time
timestamp = mxDT.strptime(lines[1][12:22], self.__date_format + cClinitek50.time_format)
_log.Log(gmLog.lInfo, 'device timestamp: %s' % timestamp)
_log.Log(gmLog.lInfo, 'system timestamp: %s' % mxDT.now())
age = mxDT.Age(mxDT.now(), timestamp)
if age.hours > 6:
_log.Log(gmLog.lErr, 'device time is off by %s, please correct that' % age)
return None
# language-unit profile
(lang, units) = string.split(lines[2], ' - ')
_log.Log(gmLog.lInfo, 'language: %s' % lang)
_log.Log(gmLog.lInfo, 'unit system: %s' % units)
# STIX type
stix_type = string.strip(lines[3])
if not stix_type in cClinitek50.known_stix_types:
_log.Log(gmLog.lErr, "don't know how to handle stix of type %s" % stix_type)
return None
# seems valid
return 1
开发者ID:ncqgm,项目名称:gnumed,代码行数:35,代码来源:Clinitek50.py
示例20:
def __xform_8303(self, request_data):
"""8303: Berichtszeit"""
if self.__request['results_reported_when'] is None:
self.__request['results_reported_when'] = mxDT.now()
self.__request['results_reported_when'] = mxDT.strptime(
request_data['8303'][0].strip(),
'%H%M',
self.__request['results_reported_when']
)
return None
开发者ID:sk,项目名称:gnumed,代码行数:10,代码来源:gmLDTimporter.py
注:本文中的mx.DateTime类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论