Google App Engine, parsedatetime and TimeZones

I am working on a Google App Engine / Django application and I ran into the following problem: In my html I have input for time. Admission is free text - the user enters "after 1 hour" or "tomorrow at 11 am". Then the text is sent to the server in AJAX, which parses it using this python library: http://code.google.com/p/parsedatetime/. After parsing, the server returns a timestamp. That's the problem - the Google App Engine always runs in UTC. So let's say that local time is 11 hours and UTC time is 2 hours. When I send "now" to the server, it will return "2am", which is good, because I want the date to be received in UTC. When I send "in 1 hour", the server will return "3am", which is also good. However, when I send β€œnoon”, the server will return β€œ12pm” because it thinks I'm talking about midday UTC - but I really need it to return 3 hours, which is noon for the sender of the request. TZ of the browser that sends the request, but that will not help me - the parsedatetime library will not accept the time zone argument (correct me if I am wrong).Walk around it? Maybe setting up the TZ environment in some way?

Thank!

+3
source share
2 answers

What you can do is add the difference using the timedelta object (http://docs.python.org/library/datetime.html)

Bias

here is some (very crude) code to give you an idea:

import parsedatetime
import datetime

my_users_timezone = whatever #replace this with a string that will make sense in the offsets dictionary

utc_timezone_offsets_in_hours = {
   'utc' : 0,
   'pacific' : -8,
   # etc
}

parsed_time = parsedatetime.whatever(input_string)
offset_hours = utc_utc_timezone_offsets_in_hours[my_users_timezone]
final_time = parsed_time + datetime.timedelta(hours=offset_hours)
return final_time
+2
source

parsedatetimethe parse procedure expects a timetuple()as a parameter sourceTimeand must carry any time zone information that you include in it, since I don’t remember to write any code that overrides it. If it is not, this is a mistake and will notify me.

You can use the code, for example, as the answer above to add a TZ offset after the procedure parse()returns what it determined the date and time to:

import parsedatetime as pdt

cal = pdt.Calendar()

start  = datetime.datetime.now().timetuple()

parsed, flag = cal.parse('in 1 hr', start)

timetuple parsed timedelta

0

Source: https://habr.com/ru/post/1783806/


All Articles