R
R
Rrooom2014-10-22 15:11:50
Django
Rrooom, 2014-10-22 15:11:50

How to set desired timezone for datetime?

The database stores data with a timestamp field - there is unix-time with UTC + 0.
It is necessary to select the given time period specified by the user, and he can choose his time zone in GMT.
For example, if we need today in UTC + 0, we take the interval:
from
time.mktime(date.today().timetuple())
to
time.mktime(datetime.now().timetuple())
A how else to make a correction for time zones &

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Egorov, 2014-10-22
@ur001

To get the current time with a time zone (localized time), you need to use now() not from datetime, but from django.utils.timezone:
To convert an already localized datetime to another time zone (for example, to the user's time zone):

from django.utils.timezone import now, pytz
user_timezone = pytz.timezone(user.timezone or settings.TIME_ZONE)
now().astimezone(user_timezone)

If you have a non- localized datetime and want to add timezone information to it:
from datetime import datetime
from django.utils.timezone import pytz
user_timezone = pytz.timezone(user.timezone or settings.TIME_ZONE)
user_timezone.localize(now())

In order for Djagno to use time zones for Date/Datetime fields, they must be enabled in the settings:
TIME_ZONE = 'Europe/Moscow'
USE_TZ = True

R
Roman no_name, 2014-10-22
@Romastr

create a list of time zones. Pacific/fiji type. That the user could choose his time zone and she signed up for him in the dock. Further, when displaying the date and time, you need to use a model or a function with the translation of the time that he chose into the server time and vice versa. It should be noted that all the data would be written in server time, that is, if a user with some time zone enters a date, for example, a call, then this date would be written not in his date, but in the date of the server.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question