日期格式化字符串:DATE_FORMAT = "%Y-%m-%d"

日期时间格式字符串:DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"

日期时间格式字符串(包含毫秒):DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S.%f"

OpenERP对象中字段赋值为当前日期(字符串):fields.date.context_today,fields.date.context_today(self, cr, uid, context=context),fields.date.today()

OpenERP对象中字段赋值为当前时间(字符串):fields.datetime.now(),fields.datetime.context_timestamp(cr, uid, datetime.now(), context=context)

OpenERP官方建议 date/datetime 的默认值的写法是fields.date.context_today,fields.datetime.now()

字符串转换为日期时间:datetime.datetime.strptime(sale.date, DATE_FORMAT)

日期时间转换为字符串:datetime.datetime.strftime(datetime.date.today(), DATE_FORMAT)

python中获取当前日期:datetime.date.today()

python中获取当前时间:datetime.datetime.now()

 

OpenERP fields 单元中对 date/datetime 类中方法定义如下所示:

 

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 DT.date.today().strftime(
            tools.DEFAULT_SERVER_DATE_FORMAT)

    @staticmethod
    def context_today(model, cr, uid, context=None, timestamp=None):
        """Returns the current date as seen in the client's timezone
           in a format fit for date fields.
           This method may be passed as value to initialize _defaults.

           :param Model model: model (osv) for which the date value is being
                               computed - automatically passed when used in
                                _defaults.
           :param datetime timestamp: optional datetime value to use 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 User/Client timezone (otherwise
                                UTC is used)
           :rtype: str 
        """
        today = timestamp or DT.datetime.now()
        context_today = None
        if context and context.get('tz'):
            tz_name = context['tz']  
        else:
            tz_name = model.pool.get('res.users').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=False) # UTC = no DST
                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 DT.datetime.now().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 use as a _defaults initializer,
           because datetime fields are automatically converted upon
           display on client side. For _defaults you :meth:`fields.datetime.now`
           should be used instead.

           :param datetime timestamp: naive datetime value (expressed in UTC)
                                      to be converted to the client timezone
           :param dict context: the 'tz' key in the context should give the
                                name of the User/Client timezone (otherwise
                                UTC is used)
           :rtype: datetime
           :return: timestamp converted to timezone-aware datetime in context
                    timezone
        """
        assert isinstance(timestamp, DT.datetime), 'Datetime instance expected'
        if context and context.get('tz'):
            tz_name = context['tz']  
        else:
            registry = openerp.modules.registry.RegistryManager.get(cr.dbname)
            tz_name = registry.get('res.users').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=False) # UTC = no DST
                return utc_timestamp.astimezone(context_tz)
            except Exception:
                _logger.debug("failed to compute context/client-specific timestamp, "
                              "using the UTC value",
                              exc_info=True)
        return timestamp
View Code

相关文章:

  • 2022-03-02
  • 2022-12-23
  • 2022-12-23
  • 2022-02-02
  • 2021-09-11
  • 2022-12-23
  • 2021-08-04
  • 2022-12-23
猜你喜欢
  • 2021-08-03
  • 2021-10-20
  • 2021-09-19
  • 2022-12-23
  • 2022-12-23
  • 2021-12-25
  • 2022-12-23
相关资源
相似解决方案