Skip to content Skip to sidebar Skip to footer

Get System Time W/timezone In Django Bypassing Default Timezone

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

Solution 1:

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

Solution 2:

To get the time for a different timezone, use this code:

# create another timezone instanceimport pytz
new_york_tz = pytz.timezone("America/New_York")

# get the current date and time, with the timezone set in your settings.pyfrom 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

Solution 3:

You can use Javascript to get the Timezone Offset from browser to UTC. Here is the code.

var d = newDate()
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.

Post a Comment for "Get System Time W/timezone In Django Bypassing Default Timezone"