我在使用 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 :
- Times are expressed in UTC (Coordinated Universal Time), with a special UTC designator ("Z").
- 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/