~openerp-dev/openobject-server/trunk-apiculture

« back to all changes in this revision

Viewing changes to openerp/osv/fields2.py

  • Committer: Raphael Collet
  • Date: 2014-05-19 13:53:03 UTC
  • Revision ID: rco@openerp.com-20140519135303-ehzgt8conxge2vh9
[ADD] fields2: method Date.context_today()

Show diffs side-by-side

added added

removed removed

Lines of Context:
26
26
from functools import partial
27
27
from operator import attrgetter
28
28
import logging
 
29
import pytz
29
30
 
30
31
from openerp.tools import float_round, ustr, html_sanitize
31
32
from openerp.tools import DEFAULT_SERVER_DATE_FORMAT as DATE_FORMAT
695
696
        return date.today().strftime(DATE_FORMAT)
696
697
 
697
698
    @staticmethod
 
699
    def context_today(record, timestamp=None):
 
700
        """ Return the current date as seen in the client's timezone in a format
 
701
            fit for date fields. This method may be used to compute default
 
702
            values.
 
703
 
 
704
            :param datetime timestamp: optional datetime value to use instead of
 
705
                the current date and time (must be a datetime, regular dates
 
706
                can't be converted between timezones.)
 
707
            :rtype: str 
 
708
        """
 
709
        today = timestamp or datetime.now()
 
710
        context_today = None
 
711
        tz_name = record._context.get('tz') or record.env.user.tz
 
712
        if tz_name:
 
713
            try:
 
714
                today_utc = pytz.timezone('UTC').localize(today, is_dst=False)  # UTC = no DST
 
715
                context_today = today_utc.astimezone(pytz.timezone(tz_name))
 
716
            except Exception:
 
717
                _logger.debug("failed to compute context/client-specific today date, using UTC value for `today`",
 
718
                              exc_info=True)
 
719
        return (context_today or today).strftime(DATE_FORMAT)
 
720
 
 
721
    @staticmethod
698
722
    def from_string(value):
699
723
        value = value[:DATE_LENGTH]
700
724
        return datetime.strptime(value, DATE_FORMAT).date()