Get system time w/timezone in Django bypassing default timezone - python

As long as I'm using plain ol' Python shell, the datetime.datetime.now() command works fine to get system's local (non-UTC) time.
But I'm working on a Django project where the time zone is changed in settings.py with TIME_ZONE = 'UTC'.
I've tried many solutions from django.utils timezone to tzlocal module, but none of them works. All of them return either incorrect or UTC time.
All of the solutions work if I change the timezone in settings.py to my local timezone. But I can't do that, so is there any way to bypass the default timezone option in settings.py? Or any way the settings.py's timezone can be automatically updated? If I remove the TIME_ZONE line, I don't know why, but it seems to get a random timezone.
EDIT -
I know that the timezone can be entered manually with pytz, but I don't want to do that. I want to get the local system timezone, but WITHOUT Django's moderation of the timezone.
Thanks.

Django seems to be putting its timezone in the TZ environment variable. Try del os.environ['TZ'] then using tzlocal.

To get the time for a different timezone, use this code:
# create another timezone instance
import pytz
new_york_tz = pytz.timezone("America/New_York")
# get the current date and time, with the timezone set in your settings.py
from django.utils import timezone
d = timezone.now()
print(d)
# get the date and time in your other timezone
d2 = new_york_tz.normalize(d)
print(d2)
See: https://docs.djangoproject.com/en/1.10/topics/i18n/timezones/#naive-and-aware-datetime-objects

You can use Javascript to get the Timezone Offset from browser to UTC. Here is the code.
var d = new Date()
var n = d.getTimezoneOffset()
alert(n)
The result is the amount of minutes. For example, you will get 480 in Los Angeles. if the result is negative number, the timezone should be the "West", opposite, the positive number means "East". AND 1 timezone = 60 minutes, so, you can figure out 480 / 60 = 8. Then the result is Los Angeles is in the west 8 timezone. Then you can use pytz to get the local time.

Related

Convert datetime to local time from Django Query to Openpyxl

Django converts the date time (I use timezone.now() to store in database) to local time in templates fine. What I need help on is when it is written to a cell in openpyxl.
Right now, I simply assign the attribute of the query to the cell.
query = SomeModel.objects.latest()
date_recorded = query.date_recorded
In templates, date_recorded is already converted to local time. No problem there.
ws.cell(row=rows, column=cols).value = date_recorded
The above code results to UTC. Please help me convert it to local time. Thank you.
I am using pytz python package.
import pytz
# UTC to IST
time_zone = pytz.timezone('Asia/Kolkata') # set timezone here
date_recorded = time_zone.localize(query.date_recorded)

Python-Django timezone is not working properly

I am working on Django based website. I am trying to get correct timezone and time to be displayed. But it is not working properly. I live in Dallas, Texas. So my default timezone is 'America/Chicago'.
My settings.py file has these lines of code.
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
I have datetime, and pytz installed. So when I am trying to save time in database, my codes are,
from datetime import datetime
import pytz
utc = pytz.utc
database = Database.objects.get(id=1)
databas.time = utc.localize(datetime.now())
database.save()
so when I check into database, updated time is 2015-10-20 23:13:04
instead of 2015-10-20 18:13:04
and when I print it out in template by codes below, I get this output Oct. 20, 2015, 1:13 p.m.
{{ database.time|localtime }}
I am confused how to use datetime, pytz and all to get accurate time along with settings.py file.
What I want to do is I want to save UTC time. But when I print out I want to get visitor's timezone and print time according to user. My website will be accessible only in United States for now. My model has
time = models.DateTimeField(auto_now_add=True)
and it is saving some different time. I have another model where I have column named expire time where I am using following codes to save,
expire_time = utc.localize(datetime.now()+ timedelta(hours=24))
means I want to expire a link after 24 hours. But this timezone is confusing me. Can anyone help me? I don't know what should I use in my codes to get proper timezone.
If you set USE_TZ = True Django stores datetimes in UTC. Use the following to create a timezone aware datetime.now:
from django.utils import timezone
from datetime import timedelta
database.time = timezone.now()
expire_time = timezone.now() + timedelta(hours=24)
You can then use activate() to set the current time zone to the end user’s actual time zone.
Have a look at "Selecting the current time zone" to see an example how a user can select his timezone and how this selection is used to activate his timezone.

How do I format a datetime to localtime in Django?

I want to format a datetime to the user's localtime. I do not want to do it in a template though, I want to do it in the .py file and pass it to the template for display as is. What facility do the template code use to do this? Can I get at this from my .py file?
You need to start using Django's Time Zones:
set USE_TZ to True
install pytz module (recommended)
set the default TIME_ZONE
Then, in order to make time-zone-aware datetimes, you need to somehow determine the user's timezone. The most reliable way would be to let the user choose the timezone and remember the choice for every user. Then, in the view activate the specific user's timezone:
import pytz
from django.utils import timezone
tzname = request.session.get('django_timezone') # or wherever you store the user's timezone
if tzname:
timezone.activate(pytz.timezone(tzname))
else:
timezone.deactivate()
print timezone.now()
Also see:
Selecting the current time zone (has the view-to-template example)
When should I activate/deactivate the current timezone in Django (1.4)?
How do I get the visitor's current timezone then convert timezone.now() to string of the local time in Django 1.4?
Hope that helps.

Converting timezone in in Python (Django) adding a mysterious 30 minutes

I have a datetime object that is set to 2014-02-24 19:00:00+00:00 and I believe this is set as UTC by default (through the Django admin panel).
This time is actually Africa/Johannesburg, so I convert it like this:
local_timezone= pytz.timezone("Africa/Johannesburg")
local_time_start = self.start_time_unix.replace(tzinfo=local_timezone)
This will now output 2014-02-24 19:00:00+01:30
Now I want to store this as the converted UTC timezone, so I do it like this:
utc_time = local_time_start.astimezone(utc)
For some reason, this outputs 2014-02-24 17:30:00+00:00. The time is should output is 17:00:00 so where is the extra 30 mins coming from?
Basically I am trying to take the given input from the django admin panel as the local timezone of the models time_zone field, but store it as UTC.
Is there a better way I can approach this? The Django docs explain how to convert the users local timezone but I need to convert it based on the timezone in the models attributes.
Don't use datetime.replace() with pytz timezones. The pytz timezones contain historical timezone data (to allow for dates in the past to use the right offsets from UTC), but datetime.replace() cannot use the correct information in that case.
Use the timezone.localize() method instead:
local_timezone = pytz.timezone("Africa/Johannesburg")
local_time_start = local_timezone.localize(self.start_time_unix)
See the pytz documentation.
Use this only on non-timezone-aware objects. For timezone aware datetime values, use datetime.astimezone() to translate value from one timezone to another:
local_timezone = pytz.timezone("Africa/Johannesburg")
local_time_start = self.start_time_unix.astimezone(local_timezone)
If you have a datetime value that has the wrong timezone attached (it should represent the given time in a different timezone, not a different time in that timezone), remove the old timezone first using .replace(tzinfo=None), then usetimezone.localize()`:
local_timezone = pytz.timezone("Africa/Johannesburg")
local_time_start = local_timezone.localize(self.start_time_unix.replace(tzinfo=None))

How to get user's local timezone other than server timezone(UTC) in python?

In OpenERP, when I try to print the current date and time, it always print the 'UTC' time. But I want to get time in the user timezone . Each user have different timezone.For example 'CST6CDT', 'US/Pacific' or 'Asia/Calcutta'. So I need to get time in user timezone so that I can show the correct datetime in the report. I have tried to change the timezone using localize() and replace() function in datatime module. But I didn't get the correct output.
Got it.
from datetime import datetime
from pytz import timezone
fmt = "%Y-%m-%d %H:%M:%S"
# Current time in UTC
now_utc = datetime.now(timezone('UTC'))
print now_utc.strftime(fmt)
# Convert to US/Pacific time zone
now_pacific = now_utc.astimezone(timezone('US/Pacific'))
print now_pacific.strftime(fmt)
# Convert to Europe/Berlin time zone
now_berlin = now_pacific.astimezone(timezone('Europe/Berlin'))
print now_berlin.strftime(fmt)
Courtesy: http://www.saltycrane.com/blog/2009/05/converting-time-zones-datetime-objects-python/
As of OpenERP 6.1 the timezone of all Python operations happening on the server-side (and in modules) is forced to be UTC. This was a design decision explained in various places [1]. The rendering of datetime values in the user's timezone is meant to be done on the client-side exclusively.
There are very few cases where it makes sense to use the user's timezone instead of UTC on the server-side, but indeed printing datetime values inside reports is one of them, because the client-side will have no chance to convert the contents of the resulting report.
That's why the report engine provides a utility method for doing so: the formatLang() method that is provided in the context of reports (RML-based ones at least) will format the date according to the timezone of the user if you call it with a datetime value and with date_time=True (it uses the tz context variable passed in RPC calls and based on the user's timezone preferences)
You can find example of how this is used in the official addons, for example in the delivery module (l.171).
Have a look at the implementation of formatLang() if you want to know how it actually does the conversion.
[1]: See the OpenERP 6.1 release notes, this other question, as well as comment #4 on bug 918257 or bug 925361.
from: http://help.openerp.com/question/30906/how-to-get-users-timezone-for-python/
DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
import pytz
from openerp import SUPERUSER_ID
# get user's timezone
user_pool = self.pool.get('res.users')
user = user_pool.browse(cr, SUPERUSER_ID, uid)
tz = pytz.timezone(user.context_tz) or pytz.utc
# get localized dates
localized_datetime = pytz.utc.localize(datetime.datetime.strptime(utc_datetime,DATETIME_FORMAT)).astimezone(tz)
DateInUTC = <~ Time variable to convert
To convert to user's timezone:
LocalizedDate = fields.datetime.context_timestamp(cr, uid, DateInUTC, context=context)
To remove the offset:
LocalizedDate = LocalizedDate.replace(tzinfo=None)

Categories