由于服务器与客户端存在时间差,而如果在服务器上直接使用date.today的话就会与客户端实际时间存在时间差,所以最佳的办法是使用下边的函数。对于datetime类似
xxxxxxxxxx
1
@staticmethod
2
def context_today(record, timestamp=None):
3
""" Return the current date as seen in the client's timezone in a format
4
fit for date fields. This method may be used to compute default
5
values.
6
7
:param datetime timestamp: optional datetime value to use instead of
8
the current date and time (must be a datetime, regular dates
9
can't be converted between timezones.)
10
:rtype: str
11
"""
12
today = timestamp or datetime.now()
13
context_today = None
14
tz_name = record._context.get('tz') or record.env.user.tz
15
if tz_name:
16
try:
17
today_utc = pytz.timezone('UTC').localize(today, is_dst=False) # UTC = no DST
18
context_today = today_utc.astimezone(pytz.timezone(tz_name))
19
except Exception:
20
_logger.debug("failed to compute context/client-specific today date, using UTC value for `today`",
21
exc_info=True)
22
return (context_today or today).strftime(DATE_FORMAT)
已复制