在Django模型中节省时区 [英] save time zone in Django Models

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

问题描述

我正在Django中创建一个表单。我必须放置一个输入类型字段,该字段仅将时区存储在数据库中(用户将从表单的下拉列表中选择时区)。我无法找到创建此时区模型的任何方法,以及如何根据保存的时区返回本地时间。我选择以下字段,但它也会同时存储分钟和秒数

I am creating a form in Django. I have to put a input type field, which only stores the timezone in database(which will be chosen by a user from a drop Down list at form). I am not able to find out any approach to create this timezone model and how it will return the local time according to saved timezone. I choose following field but it stores also minute hours and second also

 timestamp = models.DateTimeField()

下拉列表应采用以下形式:
...
GMT +5:30
GMT +6:00 ...以此类推。

Drop down list should be in form of : ... GMT +5:30 GMT +6:00...and so on.

推荐答案

django和python都不为您提供一组时区

Neither django nor python provide a set of timezones for you to use.

为此,您将需要一个附加模块,例如 pytz 。您可以像这样获取所有时区的列表:

For that, you will need an additional module like pytz. You can get a list of all timezones like this:

>>> import pytz
>>> pytz.all_timezones ['Africa/Abidjan', 'Africa/Accra', 'Africa/Addis_Ababa', 'Africa/Algiers', 'Africa/Asmara',
'Africa/Asmera'....

您可以将他们的时区名称存储在 CharField 中。

You can their store the timezone name in a CharField.

顺便说一下,在格林尼治标准时间+6:00之前选择时区并不是一个好主意。例如,EST通常比格林尼治标准时间晚5个小时,但是在夏令时更改前后的2周中,偏移量是不同的。另外,在每年的某些时候,昆士兰州的某人和新南威尔士州的某人都具有相同的格林尼治标准时间偏移,但是由于新南威尔士州具有夏令时,昆士兰州没有,因此半年内他们的格林尼治标准时间偏移是不同的。列出时区的唯一安全方法是列出实际的地理时区。

By the way, choosing a timezone by "GMT +6:00" is not a good idea. For example, EST is usually 5 hours behind GMT, but for 2 weeks around daylight savings time changes, the offset is different. Also, at some times of year someone in Queensland and someone in New South Wales both have the same GMT offset, but because NSW has DST and Queensland doesn't, for half the year their GMT offsets are different. The only safe way to list timezones is to list the actual geographic timezones.

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

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