mongo-日期类型(2)

mongo-日期类型(1)

当通过mongo shell来插入日期类型数据时,使用new Date()和使用Date()是不一样的:

> db.tianyc04.insert({mark:1, mark_time:new Date()})
> db.tianyc04.insert({mark:2, mark_time:Date()})
> db.tianyc04.find()

{ "_id" : ObjectId("5126e00939899c4cf3805f9b"), "mark" : 1, "mark_time" : ISODate("2013-02-22T03:03:37.312Z") }
{ "_id" : ObjectId("5126e00c39899c4cf3805f9c"), "mark" : 2, "mark_time" : "Fri Feb 22 2013 11:03:40 GMT+0800" }

>

我们看:使用new Date(),插入的是一个isodate类型;而使用Date()插入的是一个字符串类型。

那isodate是什么日期类型的?我们看这2个值,它比字符串大概少了8小时。这是由于mongo中的date类型以UTC(Coordinated Universal Time)存储,就等于GMT(格林尼治标准时)时间。而我当前所处的是+8区,所以mongo shell会将当前的GMT+0800时间减去8,存储成GMT时间。

如果通过get函数来获取,那么mongo会自动转换成当前时区的时间:

> db.tianyc04.findOne({mark:1})
{
"_id" : ObjectId("5126e00939899c4cf3805f9b"),
"mark" : 1,
"mark_time" : ISODate("2013-02-22T03:03:37.312Z")
}
> db.tianyc04.findOne({mark:1}).mark_time
ISODate("2013-02-22T03:03:37.312Z")
> x=db.tianyc04.findOne({mark:1}).mark_time
ISODate("2013-02-22T03:03:37.312Z")
> x
ISODate("2013-02-22T03:03:37.312Z")
> x.getFullYear()
2013
> x.getMonth() # js中的月份是从0开始的(0-11)
1
> x.getMonth()+1
2
> x.getDate()
22
> x.getHours() #注意这里获取到的小时是11,而不是3
11
> x.getMinutes()
3
> x.getSeconds()
37

ISO的日期类型可以直接使用new Date来进行比较,直接使用+8后的时间即可(注意字符串使用“/”分隔符):

> db.tianyc04.find({mark_time:{$gt: new Date('2013/02/22 11:03:37')}})
{ "_id" : ObjectId("5126e00939899c4cf3805f9b"), "mark" : 1, "mark_time" : ISODate("2013-02-22T03:03:37.312Z") }
> db.tianyc04.find({mark_time:{$lt: new Date('2013/02/22 11:03:37')}})
> db.tianyc04.find({mark_time:{$lt: new Date('2013/02/22 11:03:38')}})
{ "_id" : ObjectId("5126e00939899c4cf3805f9b"), "mark" : 1, "mark_time" : ISODate("2013-02-22T03:03:37.312Z") }
> db.tianyc04.find({mark_time:{$gt: new Date('2013/02/22 11:03:37'), $lt: new Date('2013/02/22 11:03:38')}})
{ "_id" : ObjectId("5126e00939899c4cf3805f9b"), "mark" : 1, "mark_time" : ISODate("2013-02-22T03:03:37.312Z") }


 

那么,如果使用python来读取isodate类型的数据,会自动转化为GMT+0800时间吗?我继续测试:

> exit
bye

C:\>python
'import site' failed; use -v for traceback
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Int
Type "help", "copyright", "credits" or "license" for more information.
>>> import pymongo
>>> conn=pymongo.Connection('10.0.0.35',20000)
>>> db=conn.test
>>> tianyc04=db.tianyc04.find()
#我们看,从python取出来的也是一个日期类型,一个字符串类型
>>> print tianyc04[0]
{u'mark_time': datetime.datetime(2013, 2, 2, 1, 52, 12, 281000), u'_id': ObjectId('510c714c045d7d8d7b6ec1bb'), u'mark': 1.0}
>>> print tianyc04[1]
{u'mark_time': u'Sat Feb 02 2013 09:52:17 GMT+0800', u'_id': ObjectId('510c7151045d7d8d7b6ec1bc'), u'mark': 1.0}
#我打印出mongo的isodate类型,发现并没有自动转换为GMT+0800时间:
>>> print tianyc04[0]['mark_time']
2013-02-02 01:52:12.281000
>>> print tianyc04[1]['mark_time']
Sat Feb 02 2013 09:52:17 GMT+0800

 

posted @ 2013-02-02 10:36  醇酒醉影  阅读(50442)  评论(3编辑  收藏  举报