在Django工作几个时区 [英] Working with several time zone in Django

查看:134
本文介绍了在Django工作几个时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发的应用程序作为目标用户美国。而且(如你所知)在美国有一个以上的时区。所以我有一些疑问:

The application I am working on has as target users USA. And (as you may know) in USA there's more than one time zone. So I have some doubts:


  • 那么我现在可以根据
    当前用户得到服务器端的当前时间? / li>
  • 如何存储 DateTime 数据以显示每位用户
    的正确时间?

  • 如何比较时间(例如: user.event.created> datetime.now())?什么时区将 .now()使用?

  • 什么TIME_ZONE应该在 settings.py 文件。

  • so how could I get the current time in server side based on the current user?
  • And how could I store DateTime data to show the correct time for every user?
  • How can I compare times (example: user.event.created > datetime.now())? What timezone will .now() use?
  • What TIME_ZONE should I set in settings.py file.

这是一个API,通过JS抓住用户的时区不是一个选择。我通过TokenAuthentication获取当前用户。

This is for an API, to grab user's timezone via JS is not an option. I get the current user via TokenAuthentication.

推荐答案

使用 UTC code> settings.py 并从Javascript中获取时区偏移量:

Use UTC for settings.py and grab their timezone offset from Javascript:

var utcOffset = -((new Date()).getTimezoneOffset()) / 60;

例如对于洛杉矶,现在 utcOffset == -7

e.g. for Los Angeles right now utcOffset == -7

不幸的是,这并不考虑夏令时间更改(偏移量更改为 -8 ),因此您可能需要在检索时确定出来才能获得 Pacific / Los_Angeles 。否则,如果您的业务很重要,您可以随时向用户询问用户。

Unfortunately this doesn't account for Daylight Savings Time changes later (offset changes to -8), so you may have to figure that out at the time of retrieval in order to get Pacific/Los_Angeles. Otherwise you could always just ask the user in a signup form if it's important for your business.

编辑:由于您使用的是API,您还可以尝试使用 IPInfoDB API 根据客户端IP地址进行地理位置定位。这并不总是完全准确的,但几乎总是能够获得正确的时区。

Since you're using an API, you could also try using the IPInfoDB API to geolocate based on client IP address. It's not always completely accurate, but almost always enough to get the correct timezone.

这篇关于在Django工作几个时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆