I'm building a web application which monitors the up times of friends on facebook in CherryPy (Python Web Framework) and I was wondering how it would be possible to get the time of a facebook user at any given time.
If I need to say that "friend A was online" at a specific time, it would need to match their timezones and hence I've been left a bit stumped.
I played around with the pytz module in python, however had no luck.
At the moment, I am retrieving the "timezone" for a user via the FQL and then adding the timezone value to a database:
user_details = fbconsole.fql("""SELECT uid, timezone, name FROM user WHERE uid = me()""")
I am wondering about a few things:
Is it possible to get the time in which friends are online through Facebook API?
Is it possible to alternatively figure out the time of the client at any given time, through using the timezone offset? (if so, how? I haven't been able to do this yet)
Thank you in advance
I was able to solve this problem myself through the following code:
from datetime import datetime
from pytz import timezone
#set user timezone (GMT +10)
user_timezone = timezone('Etc/GMT+10')
#convert local time to user time
user_timezone_time = user_timezone.localize(datetime.now())
#format in 12hr time (%I for 12 hour time and %p for AM PM clarification)
formatted_user_timezone = user_timezone_time.strftime('%Y-%m-%d %I:%M:%S %p %Z%z')
print formatted_user_timezone
This allowed me to retrieve the timezone field from the "user" field for the Facebook API and then apply it with the code above, to find out the local time of a facebook user.
Thanks! I hope this helps others.
Related
I know there are quite a few questions about Date/Time with Flask/SQLAlchemy and Postgres, but I have a problem that I just can't quite figure out. So, with my project I am downloading statistics from ESPN. All their game times, rightly so, are in UTC format. Example: 2020-11-26T02:56Z
So, I add this to me DB in a field of "timestamp with time zone" which I've learn is almost the standard. So, my issue I have is I'm trying to display a list of what games are "today" and I'm in the central time zone of America. I don't know how to offset my filter request for this. So, two questions:
should I keep the db format of timestamp with time zone and then figure out a way to filter those based on current day, central time zone, of those games
or
just convert the game times to Central Time before inserting them into my db. I don't foresee using this app outside of my current time zone, but I'm not 100% sure of that.
Am I just missing something obviously easy? When I view the db in PG Admin 4, the date/times are my timezone (db is on my laptop), but the api I'm writing returns json with it being UTC time.
This is what I originally tried, but obviously didn't work:
events = Event.query.filter(Event.gamedate > pytz.utc.localize(datetime.today()- timedelta(days=1)),Event.gamedate < pytz.utc.localize(datetime.today() + timedelta(days=1))).all()
When you load an UTC timestamp into timestamp with time zone, you have to set the timezone parameter correctly in that session:
SET timezone = 'UTC';
Why does Firebase add one hour to the value when adding to a timestamp?
I have a python script that put some values into a colllection in a Firestore database. The data includes a timestamp. (See python code here:)
def insertIntoFirebase(yrRow):
#myDate = dateutil.parser.parse(yrRow.fromDate)
myDate = datetime.strptime(yrRow.fromDate, '%Y-%m-%dT%H:%M:%S')
print("Tiden " + str(myDate))
doc_ref = db.collection('yrData').document(str(yrRow.index))
doc_ref.set({'index':yrRow.index ,"timeText": yrRow.fromDate,'time': myDate,
'temperature':yrRow.temperature})
In this method i put some values into the firestore collection YrData. Look at the KeyValue pair time and timeText
When looking in the Firestore database the value for the keyvalue pair time is 2020-01-16T23:00:00 witch is the correct datetime and what i want to store to the database. This is stored as a string in the firestore database. The problem is the keyvaluepair timeText witch is stored as a Firebase Timestamp. (See screenshot)
When looking at the Firestore for the keyvalue pair time the value is not what i put into the datbase. It is my value + 1 hour. (See screenshot)
When getting the dates from the Firestore documents in Swift, it is also one hour added to the timestamp. :(
The server running the python script, my computer running the browser and my MacBook running the swift code have all the same timezone.
Edit: changed some mistakes and added the last paragraph about timezone
Your code is formatting timeText according to the timezone configured on machine that's formatting the date (maybe UTC?). The Firestore console formats timestamps according to the timezone of the machine running the browser (UTC+1). These are apparently different timezones, different from each other by 1 hour. This is a common misunderstanding - it comes up a lot on Stack Overflow.
Note that a Timestamp object doesn't contain any timezone information. It is just an offset from unix epoch time. In order to format a human-readable time from it, a timezone needs to be assumed, which is where you run into apparent differences in time.
I found the error. Python doesnt really care what timezone your are on and have a "strange" implementation of timezone generally. To fix this issue i had to make python aware of the wanted timezone . (Even though it is set on the server running the script). The code bellow fixes my issue.
myDate = datetime.strptime(yrRow.fromDate, '%Y-%m-%dT%H:%M:%S')
tz = pytz.timezone('Europe/Oslo')
aware_datetime = tz.localize(myDate
This is my first time developing a timezone aware web app. I'm using Django 1.11.7. I have looked through many posts regarding timezones and honestly, I'm starting to feel like I just don't understand the concept of timezones... 0_o
I'm making a booking app with start_time and end_time for each reservation.
I expect the user to be able to enter dates and times as he experiences them in his timezone. On the other hand, I want these dates and times stored in a postgresql database in UTC format.
If I was choosing to reserve, for example, between 12am and 2am (today), the result in the database should show between 5pm and 7pm (today).
Right?
Django Internationalization settings:
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_TZ = True
USE_L10N = True
USE_I18N = True
During database creation:
start_time TIMESTAMP WITH TIME ZONE NOT NULL,
end_time TIMESTAMP WITH TIME ZONE NOT NULL
Using Django's built in admin page feature, I enter the following information:
But when I look up the results in the database, here's what I get:
2017-12-05 19:00:00-05 | 2017-12-05 20:59:59-05
The stored result changed in the opposite direction of what I was expecting. I was expecting:
2017-12-06 05:00:00+05 | 2017-12-06 07:00:00+05
If my expectations are wrong and everything is working fine, I would be grateful if you could explain to me how I should interpret the timezone when I read it.
Otherwise, if my expectations where right, I would appreciate any advice.
Thank you.
The basic issue here is that you've misunderstood what the admin is doing for you ("I expect the user to be able to enter dates and times as he experiences them in his timezone"). In fact, the admin interprets all datetimes in the server time zone (UTC in your case).
Note: You are 5 hours behind server time
actually means:
Warning: The values you enter here will be interpreted in the server timezone, which is 5 hours ahead of you.
(I agree with you that this wording is ambiguous. You might want to file a ticket about improving it.)
For background on this issue, see this ticket. The root of the problem is that there's no way to get the user's timezone in the browser. What you can do is compare the current time in the browser to the current time on the server and post the warning above if they are different.
If you want to interpret datetimes in the user's timezone, there's no alternative but to ask the user to indicate their timezone explicitly, record it somewhere, and then activate() it to make it the current timezone. This is the technique described in the documentation. I believe that there are third-party packages that provide timezone selection widgets based on the list of timezones in pytz.
You're also misreading the time display. I think what you were expecting is 2017-12-06 05:00:00+00. Instead the result is 2017-12-06 00:00:00+00 in UTC or, equivalently, 2017-12-05 19:00:00-05 in Ottawa time, which is what you reported.
https://www.google.co.jp/search?dcr=0&q=ottawa+timezone&spell=1&sa=X&ved=0ahUKEwjX0LnA5_bXAhVFjJQKHXCdBDYQvwUIJigA&biw=1394&bih=803
Ottawa timezone is -5.
You can manually test in a template that's the timezones are properly registered by showing the time you've registered in different timezones with this filter:
https://docs.djangoproject.com/en/1.11/topics/i18n/timezones/#std:templatefilter-timezone
I had a very similar issue with Hotel bookings. This answer put me on the right track.
https://stackoverflow.com/a/18307581/4660189
The key here is in what you said:
I expect the user to be able to enter dates and times as he experiences them in his timezone.
"his timezone" would need to be handled via a middleware. So that each user can be assigned a timezone, and thus the system would handle all times/dates for this user accordingly.
This should get you going. Happy coding and welcome to the mind bending reality of timezones.
I am working on Python/Django project. I am trying to let user select date and time using jQuery plugin datetimepicker add-on. So when I select now option and post data django is saving the time in UTC offset. This is what is saved in database, 2017-03-30 13:38:00+00:00. I need to convert this time from user's timezone and save it in system as utc. Because later I will have script running which will look for data in database which is less than the utc time.
Actually the script is to let user post information on website and let them chose the publish date and time. So for example, If use posted an article which will be published on April 2nd 1pm Chicago time, I don't want other users to read the article before this time. So people around the world can read article as soon as it is April 2nd and 1PM in Chicago. So how can I make this functionality work?
My solution was to get the time and remove it's timezone information using replace(tzinfo=pytz.timezone('America/Chicago')) and when I print the time, I am getting 2017-03-30 13:38:00-05:51. The actual offset right now is -05:00. Can anyone help me to and tell me what I am doing wrong?
What I am doing for form is that I have publish_date object in my model and I am using django forms to create form. I have added class as an attribute in it and using jquery plugin,
$('.datepicker').datetimepicker({
timeFormat: 'HH:mm',
stepHour: 1,
stepMinute: 1,
});
So when User submits the form, on post method this my code,
form = PublishForm(request.POST)
if form.is_valid():
f = form.save(commit=False)
f.created_by_user_id = request.user.id
f.save()
and than to get the date all I am doing is f.publish_date and the other options I have used lice replace and localize are pretty standard.
Thanks
As noted in the comments, you appear to have two problems. First is that the datetimepicker is saving a date and time with a UTC timezone offset, when it should be applying a different timezone or leaving off the timezone offset entirely. Second is that pytz is using the wrong offset.
I don't know how to fix the first problem, but I can help you with the second. You need to use pytz's localize function. This only works when the datetime doesn't have a timezone attached, but since you know the timezone is incorrect anyway you can delete it first.
tz = pytz.timezone('America/Chicago')
dt = tz.localize(dt.replace(tzinfo=None))
The naming of the datetime replace(tzinfo = ...) function is unfortunate. In fact, its behaviour is random. Do not use this!
Mark's answer is the way to go. Use localize.
I am using: datetime.now() to get the current time in an Event app that lets you create an event that has an end date, then all of the events are displayed in a calendar and if an event is passed due it is displayed in red.
My issue is that I have some users in different timezones than me saying that the events are ending at the wrong time. They should end at midnight on the day they are due.
I have the timezone setup in my django settings.py. When I use: datetime.now() is that going off of the users local timezone or is it going off of what timezone I have setup in django?
What I want is to find midnight for the users current timezone, so if my method above is wrong, how do I go about doing that?
Thanks
You will need your users to specify their timezone in their user profile. This can then be used to calculate local times correctly.
Check out Relativity of time – shortcomings in Python datetime, and workaround for some good information (and concrete examples).
UPDATE: From Django 1.4 it comes up with timezone support. Check it out.
I worked on a library to work with user timezones transparently. You should just use a Field and some timezone utils and you should get everything converted to the user timezone everytime you do a request or a query.
The library is named django-timezones, and is a modification of the one that Brosner first made.
Give it a try to see if it works for you.
Try storing the UTC Datetime instead then make the necessary adjustments based on the user's timezone:
import datetime
def getUtcNow():
return datetime.datetime(*time.gmtime()[:6])