Python/Mongoengine - 保存到数据库时缺少时区?

标签 python mongoengine python-dateutil

我在使用 MongoEngine 将日期对象保存到 Mongo 时遇到一些问题。这是我的代码:

print isodate
>>> 2014-07-01T20:00:00.000Z

import pytz
from dateutil import parser

tz = pytz.timezone('Europe/London')
start = parser.parse(isodate).replace(tzinfo=None)
start = tz.localize(start)

print start
>>> 2014-07-01 20:00:00+01:00

本地化日期似乎工作正常,但保存到 Mongo 时:

f = Fixture(
    start=start
)

当我查看创建的 Mongo 文档时,出现以下奇怪的情况:

{
  _id: ObjectId("53b1dfbde20b47102c824a8f"),
  start: ISODate("2014-07-01T19:00:00Z")
}

是否有任何原因导致时间偏差两个小时,并且时区不再存在?

最佳答案

我觉得您误解了日期时间格式。引用W3C Date and Time Formats :

  1. Times are expressed in UTC (Coordinated Universal Time), with a special UTC designator ("Z").
  2. Times are expressed in local time, together with a time zone offset in hours and minutes. A time zone offset of "+hh:mm" indicates that the date/time uses a local time zone which is "hh" hours and "mm" minutes ahead of UTC. A time zone offset of "-hh:mm" indicates that the date/time uses a local time zone which is "hh" hours and "mm" minutes behind UTC.

“2014-07-01T20:00:00.000Z”应等于“2014-07-01 21:00:00+01:00”。所以它在本地化日期时间时出错,而不是在保存到 Mongo 时出错。

如果您想将“....T....Z”转换为本地时间,您可以尝试以下操作:

print isodate
>>> 2014-07-01T20:00:00.000Z
import pytz
from dateutil import parser
local_tz = pytz.timezone('Europe/London')
local_time = parser.parse(isodate).astimezone(local_tz)
print local_time
>>> 2014-07-01 21:00:00+01:00

如果需要对本地时间进行日期运算,请再执行一步(引用:pytz doc):

local_tz.normalize(local_time)

其实你可以直接将“....T..Z”ISODate保存到Mongo中,而不需要转换为本地时间。由于它已经包含时区信息,因此无需转换。

关于Python/Mongoengine - 保存到数据库时缺少时区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24499792/

相关文章:

python - 计算文件中的大写字母、小写字母、数字和空格

python - 无法从另一个 python 代码访问 ListField 元素

Python/Flask/MongoEngine DateTimeField

python - 使用 dateutil.parser 解析另一种语言的日期

python - 使用变量切片字符串,Typerror : string indices must be integers

Python 正则表达式反向引用命名组

python - 使用正则表达式从Python字符串中提取模式

python - Mongoengine 文档作为 EmbeddedDocument

python - 值错误 : RRULE UNTIL values must be specified in UTC when DTSTART is timezone-aware

python - 从单个字符串中分离两个日期时间值