简体   繁体   English

Django自动将日期时间字符串转换为本地时区

[英]Django automatically converting datetime string to local timezone

I am adding timestamp in my payload and storing it in the database for every record. 我将时间戳添加到我的有效负载中,并将其存储在数据库中以获取每条记录。

Suppose say a part of my payload is {"content":[{"timestamp":"2017-12-12 08:05:30"}] 假设说我的有效载荷的一部分是{"content":[{"timestamp":"2017-12-12 08:05:30"}]

This is how I process it. 这就是我的处理方式。

content['timestamp'] = parser.parse(content['timestamp'],dayfirst=True)

My model has timestamp field as : 我的模型的时间戳字段为:

timestamp = models.DateTimeField(null=True)

When I check in my database it stores timestamp field as : 当我检查数据库时,它将时间戳字段存储为:

2017-12-12 13:35:30

Which should be stored as it is as per my requirement. 根据我的要求应按原样存储。 2017-12-12 08:05:30

ie it stores the timestamp field + my local timezone(+5:30) hours. 即它存储时间戳字段+我的本地时区(+5:30)小时。

I want it to store the timestamp field as it is. 我希望它按原样存储时间戳字段。

I tried other posts where they suggest using del os.environ['TZ'] . 我尝试了其他建议使用del os.environ['TZ']帖子。

Any idea what I may have done which causes this or what could I do to avoid this. 我可能做过什么导致这种情况的任何想法,或者我应该怎么做才能避免这种情况。

Any help is appreciated. 任何帮助表示赞赏。

So according to this Question the problem is when django converts datetime to postgres timestamptz in the database. 所以根据这个问题,问题是当django在数据库中将datetime转换为postgres timestamptz时。

Postgres prevent timestamp with timezone conversion Postgres通过时区转换防止时间戳记

So I need to have timestamp field in PostgreSQL 所以我需要在PostgreSQL中有时间戳字段

In order to do that , I need to use the answer posted in this question. 为此,我需要使用此问题中发布的答案。

Can we have django DatetimeField without timezone? 我们可以有没有时区的Django DatetimeField吗?

Where I need to specify USE_TZ = False in the settings. 我需要在设置中指定USE_TZ = False的地方。

This makes sure while migrating PostgreSQL considers datetimefield to be converted to timestamp and not timestamptz . 这可以确保在迁移时PostgreSQL认为datetimefield被转换为timestamp而不是timestamptz。

You can set a timezone in settings.py 您可以在settings.py中设置时区

Here is the list of valid timezones: 以下是有效时区的列表:

http://en.wikipedia.org/wiki/List_of_tz_database_time_zones http://en.wikipedia.org/wiki/List_of_tz_database_time_zones

You can use 您可以使用

TIME_ZONE = 'Asia/Calcutta' TIME_ZONE ='Asia / Calcutta'

for UTC+05:30 适用于UTC + 05:30

Reference from Selcuk Answer 来自塞尔丘克的答复

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM