本文整理汇总了Python中mx.DateTime类的典型用法代码示例。如果您正苦于以下问题:Python DateTime类的具体用法?Python DateTime怎么用?Python DateTime使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DateTime类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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')
示例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
示例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
示例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')
示例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])
示例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
示例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
示例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
示例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
示例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
示例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')
示例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)
示例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
示例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]
}