How do I get website to display local time? - python

If I run this in VS Code, it gives me the correct local time:
from time import strftime
time = strftime("%H:%M %p")
print(time)
But if I use the same code in a Django project, my website displays a time which is 8 hours behind local time.
from time import strftime,localtime
def time_display(request):
context = {
"date":strftime("%b %d, %Y",localtime()), #DOESN'T DISPLAY LOCAL TIME
"time1": strftime("%H:%M %p",localtime()), #DOESN'T DISPLAY LOCAL TIME
"time3": strftime("%H:%M %p"), #DOESN'T DISPLAY LOCAL TIME
}
return render(request,'time_display.html',context)
How do I fix it to display correct local time where the webpage is being viewed?

Not an expert but you can change setting.py file like:
TIME_ZONE = 'Europe/London'
note: change Europe/London to your time zone.
You can find a list of timezone names here: http://en.wikipedia.org/wiki/List_of_tz_database_time_zones

Related

i'm trying to convert my local windows system timezones to uk timezone using python

i'm trying to convert whatever the user select time timezone it should convert into uk timezone. I've found a package in python called "pytz" but the list of timezones are different from my windows local system timezones. I've searched for micorsoft default system timezones and trying to convert them in uk timezones
please click the below link for microsoft default system timezone details.
https://learn.microsoft.com/en-us/windows-hardware/manufacture/desktop/default-time-zones?view=windows-11
for example instead passing 'Asia/Kolkata' to my "get_uk_time" function i'm trying to pass windows local system timezone as "Chennai, Kolkata, Mumbai, New Delhi" or India Standard Time or IN. similar way for other timezones which are available in the microsoft link above
i've tried below approch but unable to find how to convert above local windows system timezones.
from datetime import datetime
from pytz import timezone
def get_uk_time(time_zone):
try:
country_tz = timezone(time_zone)
format = "%Y, %m, %d, %H, %M, %S"
time_now = datetime.now(timezone(time_zone))
format_time = time_now.strftime(format)
london_tz = timezone('Europe/London')
local_time = country_tz.localize(datetime.strptime(format_time, format))
convert_to_london_time = local_time.astimezone(london_tz)
uk_time = convert_to_london_time.strftime('%H:%M')
return uk_time
except:
print('unable to find the timezone')
my_json = {'timezone': 'Asia/Kolkata'}
time_zone = my_json['timezone']
time_in_london = get_uk_time(time_zone)
print(time_in_london)
please help.

Django/Apache old content after restart

I have a strange problem with a website running on Django 1.8 and Apache.
I am trying to display a list of next week's upcoming events. After making modifications to the model, making and applying my migrations on the website, and restarting Apache, everything shows up fine. I have a python script queries and displays next week's days worth of events on the website. This week-to-week rollover of events is scheduled to happen shortly after midnight on the Saturday before the events take place.
Unfortunately, the events are not showing up on Saturday until I manually reload the Apache service. Also, by the time Monday rolls around, the site is again displaying old information until I again reload the Apache service. After the Monday reload, everything works as it should until the next Saturday.
I've checked all the crons, and there's nothing running that should make the site behave this way. I've also checked the ctime and mtime on all of the files and it does not appear that they've been changed or modified. I've also checked through the script and can find nothing that would be causing this behaviour.
Does anyone know what might be causing this or have another approach to solving this problem?
Thank you.
Here's the relevant code...
views.py
def index(request, starttime = datetime.now(), version = False):
# starttime: Datetime object for when to begin looking for events. Index pages are always a week.
starttime = datetime.now()
endtime = starttime + timedelta(7)
event_list = getEventsDB(EventList(), start = starttime, end = endtime)
event_calendar = getEventsDB(
EventSeries.objects.get(event_slug = 'competition'),
start = starttime, end = starttime + timedelta(7))
highlight_title = 'Competitions'
t = loader.get_template('event/index.html')
c = RequestContext(request, {
'page_title': 'Events',
'highlight_title': highlight_title,
'event_list': event_list,
'highlight': event_calendar,
'event_series_list': EventSeries.objects.filter(active=True),
})
return HttpResponse(t.render(c))
Your problem is here:
def index(request, starttime = datetime.now(), version = False):
There starttime is evaluated when the method is defined, which happens when the module is first imported - in other words, when the server is restarted. Don't put values there; instead, leave the default as None and check in the function itself:
def index(request, starttime=None, version = False):
if starttime is None:
starttime = datetime.now()

Convert UTC time into local time using python

i want to convert UTC time into user's browser time.
i have tried a loat but its display me system time only.
working with django application. can anybudy help me out.
import pytz
from tzlocal import get_localzone
def utc_to_local(utc_dt):#utc_dt that is UTC time
local_tz = get_localzone()
print local_tz #that is display system timezone inplace of USER's timezone
I have tried with below code.
import time
from datetime import datetime
from dateutil import tz
utc = datetime.strptime(str(utc_dt)[:19], '%Y-%m-%d %H:%M:%S')
return time.mktime(utc_dt.timetuple()) * 1000
convert utc time into second and then using javascript need to make it localtime. but conversion value not accurate and its display me wrong date.
Javascript code.
//1449206930000 #Seconds when above code run
//1449226703.79 #that is correct >> time.time() in python = 1449226703.79
#below code give perfact output
var date = new Date(parseInt(1449226703.79, 10) * 1000);
console.log(date);
#below code not working
var date = new Date(parseInt(1449206930000, 10) * 1000);
console.log(date);
Regards
You need to find the users timezone first, to convert time in there local timezone.
There are two ways to do it.
1) Pass simply UNIX-timestamp then use a Javascript to convert it in human readable time on the browser momentjs can help you with that.
function human_time(unixtime, tz) {
var t=moment.unix(unixtime);
return t.tz(tz).format('DD/MM/YY HH:mm:ss');
}
2) Use IP address or HTTP headers to detect the user location and then use pytz to convert your time in users system timezone instead of your own django/server timezone.
def get_user_timezone(request):
return request.visitor.location.timezone
def human_time(dt, tz="Asia/Kolkata"):
try:
tz = pytz.timezone(tz)
except:
tz = pytz.timezone("Asia/Kolkata")
dt = dt.astimezone(tz)
return dt.strftime(r'%d/%m/%Y %H:%M:%S %Z')
def view_get_local_time(request):
tz = get_user_timezone(request) #detect user timezone, base on IP
text = human_time(timezone.now(), tz) #convert server-time to detected timezone
return HttpResponse(text)
Note: First method is the most preferable method.
import time, calendar
import datetime
utc = datetime.datetime.strptime(str(timezone_rt)[:19], '%Y-%m-%d %H:%M:%S')
return time.mktime(time.localtime(calendar.timegm(utc.timetuple()))) #convert utc time into second that correct output like function time.time()
Thanks for help.

Does django mess up with python's datetime?

I have a file that I check it's creation time using ctime. Here is the snippet of code (not complete, just the important part):
import time
import pytz
import os
from datetime import datetime
myfile = SOMEWHERE
myfile_ctime = os.path.getctime(myfile)
d = datetime.strptime(time.ctime(myfile_ctime), '%a %b %d %H:%M:%S %Y')
# d here is Tue Mar 25 00:33:40 2014 for example
ny = pytz.timezone("America/New_York")
d_ny = ny.localize(d)
mytz = pytz.timezone(MY_TZ_WHATEVER)
myd = d_ny.astimezone(mytz)
final_date = myd.strftime('%Y-%m-%d %H:%M:%S')
print(final_date + "some string")
# is now 2014-03-25 01:33:40some string, correctly with the timezone.
When this is run as a simple python script, everything is ok. But when I run the same code inside a function in a templatetags/myfile.py that renders to a template in a Django App, when trying to get the date from time.ctime(myfile_ctime), then I get Tue Mar 25 04:33:40 instead of Tue Mar 25 00:33:40 from the snippet above (the code is the same in the standalone script and in Django - and I concatenate the date with another string).
My question is: I'm using just Python standard libraries, same snippet of code in both places, reading the same file in the same environment. Why the difference? Do settings in settings.py mangles up something in the standard libraries? Just being in a Django environment it changes how standard libraries should work? Why when calling standalone everything works as it should?
(I'm behind apache, don't know if this is relevant)
Make sure of the Time Zone settings in settings.py, for more info about Django Time Zone Settings, check this page: https://docs.djangoproject.com/en/1.6/ref/settings/#time-zone
In ./django/conf/__init__.py:126:, TZ environment variable is set based on settings.py.
os.environ['TZ'] = self.TIME_ZONE
My TIME_ZONE is UTC.
That's why a standalone script result is different from a snippet inside Django: when running standalone, this environment variable TZisn't set.
Now, when creating a datetime object from a myfile_ctime, I just need to add tzinfo from my server (/etc/sysconfig/clock). My code now looks like this:
import time
import pytz
import os
from datetime import datetime
myfile = SOMEWHERE
myfile_ctime = os.path.getctime(myfile)
ny = pytz.timezone("America/New_York")
d = datetime.fromtimestamp(myfile_ctime, tz=ny)
mytz = pytz.timezone(MY_TZ_WHATEVER)
myd = d.astimezone(mytz)
final_date = myd.strftime('%Y-%m-%d %H:%M:%S')
I hope this is useful to someone. As always, read the source. :)

Using python-twitter library, how to set timezone?

I'm trying to list out tweets with their time-stamps. I have this...
#!/usr/bin/python
import twitter
api = twitter.Api()
statuses = api.GetUserTimeline('ttytter')
for s in statuses:
print s.created_at + " " + s.text
Which prints out...
Sat Oct 20 04:56:47 +0000 2012 #uriel1998 W/r/t DMs, they appear just fine in 2.0.4 and 2.1 beta here, near as I can tell.
Which is pretty much what I'm after, but for the time, which seems to be in the wrong timezone. https://twitter.com/ttytter/status/259518502069760000
Is there a way I can change this within the python-twitter library? I was looking at GetTimeZone() and SetTimeZone(), but I haven't been able to figure out how they work.
Also looking at how to shift a datetime object by 12 hours in python but not sure if I need to go there.
Thanks for any help!
python-twitter returns the status timestamps as a string and as the number of seconds since the epoch. The latter is the simplest to convert to a timezone-aware datetime instance (see this answer).
Unfortunately the user's time_zone attribute is not in the standard tz database format used by pytz, so it is necessary to use the utc_offset user attribute instead (we still use the time_zone attribute to name the tzinfo created with with the UTC offset). The python-dateutil package provides a convenience type tzoffset that allows the creation of tzinfo instances from UTC offsets, which we can then use to convert the datetime from UTC to the local time zone:
import pytz
import twitter
from datetime import datetime
from dateutil.tz import tzoffset
USERNAME = 'ttytter'
api = twitter.Api()
# get a 'tzinfo' instance with the UTC offset for the user's local time
user = api.GetUser(USERNAME)
localtime_tz = tzoffset(user.time_zone, user.utc_offset)
statuses = api.GetUserTimeline(USERNAME)
for s in statuses[:1]:
# get UTC timestamp from seconds since epoch
utc_dt = datetime.utcfromtimestamp(s.created_at_in_seconds).replace(tzinfo=pytz.utc)
print('utc: {}'.format(utc_dt))
# convert to local time in the user's timezone
localtime_dt = utc_dt.astimezone(localtime_tz)
print('localtime [{}]: {}'.format(localtime_dt.tzname(), localtime_dt))
which gives the output for the first status:
utc: 2012-10-20 04:56:47+00:00
localtime [Pacific Time (US & Canada)]: 2012-10-19 20:56:47-08:00
Combining suggestions from Pedro Romano and J.F. Sebastian, I have this...
import pytz
import twitter
from datetime import datetime
USERNAME = 'ttytter'
api = twitter.Api()
user = api.GetUser(USERNAME)
pst_tz = pytz.timezone('America/Los_Angeles')
statuses = api.GetUserTimeline(USERNAME)
for s in statuses[:1]:
# get UTC timestamp from seconds since epoch
utc_dt = datetime.utcfromtimestamp(s.created_at_in_seconds).replace(tzinfo=pytz.utc)
# convert to given timezone
pst_dt = pst_tz.normalize(utc_dt.astimezone(st_tz))
print(pst_dt.strftime('%Y-%m-%d %H:%M:%S ')) + s.text
Output: 2012-10-19 21:56:47 #uriel1998 W/r/t DMs, they appear just fine in 2.0.4 and 2.1 beta here, near as I can tell. which is the correct time zone and also accounts for DST.
Thank you!

Categories