gpt4 book ai didi

django - Google App Engine、parsedatetime 和 TimeZones

转载 作者:太空宇宙 更新时间:2023-11-03 15:35:49 25 4
gpt4 key购买 nike

我在开发 Google App Engine/Django 应用程序时遇到了以下问题:在我的 html 中,我输入了时间。输入是自由文本——用户键入“1 小时内”或“明天上午 11 点”。然后将文本发送到 AJAX 中的服务器,服务器使用此 python 库对其进行解析:http://code.google.com/p/parsedatetime/ .解析后,服务器返回时间的纪元时间戳。这就是问题所在 - Google App Engine 始终在 UTC 上运行。因此,假设本地时间现在是上午 11 点,UTC 时间是凌晨 2 点。当我将“现在”发送到服务器时,它会返回“凌晨 2 点”,这很好,因为我希望以 UTC 时间接收日期。当我发送“1 小时内”时,服务器将再次返回“凌晨 3 点”,这很好。但是,当我在“中午”发送时,服务器将返回“12pm”,因为它认为我在谈论中午 UTC - 但实际上我需要它返回凌晨 3 点,这对请求发送者来说是中午。我可以继续发送请求的浏览器的 TZ,但这不会真正帮助我 - parsedatetime 库不会采用时区参数(如果我错了请纠正我)。有没有绕过这个?也许以某种方式设置环境 TZ?

谢谢!

最佳答案

您可以做的是使用 timedelta 对象添加差异 (http://docs.python.org/library/datetime.html)

偏移量

这里有一些(非常粗略的)代码可以给你这个想法:

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

关于django - Google App Engine、parsedatetime 和 TimeZones,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4612635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com