odoo开发笔记-日期时间相关操作

更新时间:2023-06-19 23:26:47 阅读: 评论:0

odoo开发笔记-⽇期时间相关操作
⽇期格式化字符串:DATE_FORMAT = "%Y-%m-%d"
⽇期时间格式字符串:DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
⽇期时间格式字符串(包含毫秒):DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S.%f"
OpenERP对象中字段赋值为当前⽇期(字符串):t_today,t_today(lf, cr, uid, context=context),day() OpenERP对象中字段赋值为当前时间(字符串):w(),t_timestamp(cr, uid, w(), context=context) OpenERP官⽅建议 date/datetime 的默认值的写法是:t_today,w()
字符串转换为⽇期时间:datetime.datetime.strptime(sale.date, DATE_FORMAT)
⽇期时间转换为字符串:datetime.datetime.strftime(day(), DATE_FORMAT)
python中获取当前⽇期:day()
python中获取当前时间:w()
OpenERP fields 单元中对 date/datetime 类中⽅法定义如下所⽰:
farfrom
class date(_column):
_type = 'date'
@staticmethod
def today(*args):
""" Returns the current date in a format fit for being a
default value to a ``date`` field.
This method should be provided as is to the _defaults dict, it
should not be called.
"""
return day().strftime(
tools.DEFAULT_SERVER_DATE_FORMAT)
@staticmethod
def context_today(model, cr, uid, context=None, timestamp=None):
"""Returns the current date as en in the client's timezone
in a format fit for date fields.
This method may be pasd as value to initialize _defaults.
:param Model model: model (osv) for which the date value is being
computed - automatically pasd when ud in
_defaults.
:param datetime timestamp: optional datetime value to u instead of
the current date and time (must be a
datetime, regular dates can't be converted
between timezones.)
:param dict context: the 'tz' key in the context should give the
name of the Ur/Client timezone (otherwi
UTC is ud)
:rtype: str
"""
today = timestamp or w()
context_today = None
if context ('tz'):
tz_name = context['tz']
el:
tz_name = ('res.urs').read(cr, SUPERUSER_ID, uid, ['tz'])['tz']
if tz_name:
try:
utc = pytz.timezone('UTC')
context_tz = pytz.timezone(tz_name)
utc_today = utc.localize(today, is_dst=Fal) # UTC = no DSTprevalent
context_today = utc_today.astimezone(context_tz)
except Exception:
_logger.debug("failed to compute context/client-specific today date, "
"using the UTC value for `today`",
exc_info=True)
return (context_today or today).strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
class datetime(_column):
_type = 'datetime'
@staticmethod
def now(*args):
""" Returns the current datetime in a format fit for being a
default value to a ``datetime`` field.
This method should be provided as is to the _defaults dict, it
should not be called.
"""
return w().strftime(
tools.DEFAULT_SERVER_DATETIME_FORMAT)
@staticmethod
def context_timestamp(cr, uid, timestamp, context=None):
"""Returns the given timestamp converted to the client's timezone.
This method is *not* meant for u as a _defaults initializer,
This method is *not* meant for u as a _defaults initializer,
becau datetime fields are automatically converted uponmaintain用法
display on client side. For _defaults you :meth:`w`
should be ud instead.
:param datetime timestamp: naive datetime value (expresd in UTC)纽约日报
误解英语
to be converted to the client timezone
:param dict context: the 'tz' key in the context should give the
name of the Ur/Client timezone (otherwi
UTC is ud)
:rtype: datetime
:return: timestamp converted to timezone-aware datetime in context
timezone
"""
asrt isinstance(timestamp, DT.datetime), 'Datetime instance expected'
if context ('tz'):
tz_name = context['tz']
el:
registry = (cr.dbname)
tz_name = ('res.urs').read(cr, SUPERUSER_ID, uid, ['tz'])['tz']
if tz_name:
try:
utc = pytz.timezone('UTC')
context_tz = pytz.timezone(tz_name)
utc_timestamp = utc.localize(timestamp, is_dst=Fal) # UTC = no DST
return utc_timestamp.astimezone(context_tz)niton
except Exception:
_logger.debug("failed to compute context/client-specific timestamp, "
"using the UTC value",
exc_info=True)
return timestamp
应⽤⽰例代码:
#⾃动获取⽇期对应的⽉份并保存
def _get_month(lf, cr, uid, ids, field_name, arg, context=None):
res = {}
if context is None:
context = {}
DATETIME_FORMAT = "%Y-%m-%d"
for sale in lf.brow(cr, uid, ids, context=context):
saledate = datetime.datetime.strptime(sale.date, DATETIME_FORMAT)
res[sale.id] = saledate.strftime('%Y') + '-' + saledate.strftime('%m')
return res
_columns={
'name':fields.char(u'单号', size=64, lect=True, required=True, readonly=True),
'date':fields.date(u'⽇期', lect=True, required=True, readonly=True),
'month':fields.function(_get_month, method=True, type='char', size=10, string = u'⽉份', store=True, invisible=True),
}
保持联系英文_defaults={
'name': lambda obj, cr, uid, context: '/',
'date':t_today,
#'employee_id':_employee_get,
'state':'draft'
}
#⾃动计算到期⽇期,按开卡⽇期加年数*365 天
def _get_due_date(lf, cr, uid, ids, field_name, arg, context=None):
res = {}
if context is None:
context = {}
DATE_FORMAT = "%Y-%m-%d"
for rec in lf.brow(cr, uid, ids, context=context):
category = rec.category
if category:
remaining_times=category.times_limit
if rec.active_date:
res[rec.id]=(datetime.datetime.strptime(rec.active_date, DATE_FORMAT) +
datetime.timedelta(days=category.age_limit*365)).strftime(DATE_FORMAT)
el:
res[rec.id]=(day()+  datetime.timedelta(days=category.age_limit*365)).strftime(DATE_FORMAT)
return res
_columns={
"name":fields.char("卡号",size=64, required=True, readonly=True, states={'0':[('readonly',Fal)]}),
"category":fields.many2one("dispatch.rvice_card_category","服务卡类型", required=True, readonly=True, states={'0':[('readonly',Fal)]}),        'age_limit':lated('category', 'age_limit', string=u'年限', type='float', readonly=True, store=True),
"times_limit":fields.integer(u"初始次数", readonly=True),
"customer":fields.many2one("dispatch.customer","客户",required=True, lect=True, readonly=True, states={'0':[('readonly',Fal)]}),
"remaining_times":fields.integer("剩余次数",required=True, readonly=True, states={'0':[('readonly',Fal)]}),
"active_date":fields.date("开卡⽇期",required=True, readonly=True, states={'0':[('readonly',Fal)]}),
'due_date':fields.function(_get_due_date, method=True, type='date', string = u'到期⽇期', store=True),
'state': fields.lection([('0', u'未开卡'),('1', u'已开卡'),('2', u'已⽤完'),('3', u'已过期'),('4', u'已锁定')], u'状态',required=True, readonly=True),
'lock_note': fields.char(u'锁定原因', size=200, invisible=Fal, readonly=True, states={'1':[('readonly',Fal)], '4':[('readonly',Fal)]}),
}
# TODO: can be improved using resource calendar method
#计算⽇期间隔对应的天数
def _get_number_of_days(lf, date_from, date_to):
"""Returns a float equals to the timedelta between two dates given as string."""
DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
from_dt = datetime.datetime.strptime(date_from, DATETIME_FORMAT)
to_dt = datetime.datetime.strptime(date_to, DATETIME_FORMAT)
timedelta = to_dt - from_dt
diff_day = timedelta.days + ds) / 86400
return diff_day
#对象字段
_columns = {
'date_from': fields.datetime(u'起始⽇期',required=True, readonly=True, states={'draft':[('readonly',Fal)]}, lect=True),
'date_to': fields.datetime(u'结束⽇期', readonly=True, states={'draft':[('readonly',Fal)]}),
go round
'days': fields.float(u'天数', digits=(8, 2), readonly=True, states={'draft':[('readonly',Fal)]}),
}
#更改起始⽇期,⾃动计算请假天数
def onchange_date_from(lf, cr, uid, ids, date_to, date_from):
"""
If there are no date t for date_to, automatically t one 8 hours later than
the date_from.
Also update the number_of_days.
"""
# date_to has to be greater than date_from
if (date_from and date_to) and (date_from > date_to):
pt_osv(_(u'警告!'),_(u'开始⽇期必须⼩于结束⽇期.'))
result = {'value': {}}
# No date_to t so far: automatically compute one 8 hours later
if date_from and not date_to:
date_to_with_delta = datetime.datetime.strptime(date_from, tools.DEFAULT_SERVER_DATETIME_FORMAT) + datetime.timedelta(hours=8)            result['value']['date_to'] = str(date_to_with_delta)
# Compute and update the number of days
if (date_to and date_from) and (date_from <= date_to):
diff_day = lf._get_number_of_days(date_from, date_to)
result['value']['days'] = round(math.floor(diff_day))+1
el:
result['value']['days'] = 0
return result
#更改结束⽇期,⾃动计算请假天数
def onchange_date_to(lf, cr, uid, ids, date_to, date_from):
"""
Update the number_of_days.
"""
外语考试# date_to has to be greater than date_from
if (date_from and date_to) and (date_from > date_to):
pt_osv(_(u'警告!'),_(u'开始⽇期必须⼩于结束⽇期.'))
result = {'value': {}}
# Compute and update the number of days
if (date_to and date_from) and (date_from <= date_to):
diff_day = lf._get_number_of_days(date_from, date_to)
result['value']['days'] = round(math.floor(diff_day))+1
el:
result['value']['days'] = 0
return result
音标发音下载

本文发布于:2023-06-19 23:26:47,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/78/994332.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:时间   字符串   更改   计算   天数   赋值
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图