Bỏ qua để đến Nội dung
Menu
Câu hỏi này đã bị gắn cờ
4 Trả lời
14640 Lượt xem

I can get the current time with:

datetime.datetime.now()

But when I print this, it is in UTC and I want it in local time.


Ảnh đại diện
Huỷ bỏ
Câu trả lời hay nhất

I found that this works for me.

A = datetime.datetime.now()  # Get the current date and time.

B = int(A.strftime("%H"))   # Extract Hours from date time and convert it to an integer.

C = int(A.strftime("%M")) * 0.01667   # Extract Minutes from date time and convert it to an integer.

 

# Correct the time offset for the 24H loop so we don’t end with negative hours.

if B == 0:

              B = 20

elif B == 1:

              B = 21

elif B == 2:

              B = 22

elif B == 3:

              B = 23

else:

              B = B – 4  # B  =  B  +/-  Time Zone offset in hours.

 

#Add Minutes back to the hours. The result is hours and minutes in an integer format.

TIME  =  B  +  C

Ảnh đại diện
Huỷ bỏ
Câu trả lời hay nhất

BEST Solution (You set your timezone in Admin User) and Use Following Code :

from odoo.tools import pytz

now_time = datetime.now()

user = self.env['res.users'].browse([2])

tz = pytz.timezone(user.tz) or pytz.utc

user_tz_date = pytz.utc.localize(now_time).astimezone(tz)

print(user_tz_date)
Ảnh đại diện
Huỷ bỏ
Câu trả lời hay nhất
timestamp = datetime.datetime.now()
assert isinstance(timestamp, datetime), 'Datetime instance expected'
tz_name = record._context.get('tz') or record.env.user.tz
utc_timestamp = pytz.utc.localize(timestamp, is_dst=False) # UTC = no DST
if tz_name:
try:
context_tz = pytz.timezone(tz_name)
return utc_timestamp.astimezone(context_tz)
except Exception:
_logger.debug("failed to compute context/client-specific timestamp, "
"using the UTC value",
exc_info=True)
Ảnh đại diện
Huỷ bỏ

Hi Hilar,

While executing the above code, getting the following error

ValueError: <class 'NameError'>: "name 'pytz' is not defined" while evaluating

you need to import pytz

Câu trả lời hay nhất

Hi,

Please check that you configured user's time zone.

For configuring the time zone

Go to the right most corner (can see logged in user name there)

Click there. there you have, preference menu. click that. and the given form will give you the option to put the time zone.

After that take the print again.

May be your problem will be solved.


Thank You

Ảnh đại diện
Huỷ bỏ
Bài viết liên quan Trả lời Lượt xem Hoạt động
Take Users Timezone Đã xử lý
3
thg 7 25
3912
Time & Date Issue Đã xử lý
6
thg 9 19
11186
2
thg 3 16
7831
0
thg 3 15
8113
1
thg 1 24
12656