MongoDB使用BSON存儲數據,當保存到mongoDB時,pymongo會自動將您的python datetime對象轉移到BSON,然後您可以使用過濾器來查詢mongoDB。
注意,文檔可以包含本機Python類型(如 datetime.datetime實例)將被自動轉換爲 和從適當的BSON類型。
因此,所有你需要的是在日期時間類型和字符串類型之間來回傳送。
使用這兩個功能,您可以檢查它在Python官方手冊:
8.1.7. strftime() and strptime() Behavior
的文檔說明你應該使用哪個參數/格式。
一些示例將幫助您更好,假設您正在使用Python 2.7:
>>> original_date_string = '22.12.2015'
>>> print type(original_date_string)
# Your original data is a string
<type 'str'>
>>> import datetime
>>> python_date_object_for_insert_mongo = datetime.datetime.strptime(original_date_string, '%d.%m.%Y')
>>> print python_date_object_for_insert_mongo
# transfer to datetime object use datetime.datetime.strptime()
# the second argument is the format of your original data
2015-12-22 00:00:00
>>> print type(python_date_object_for_insert_mongo)
# see, it's a native python datetime object
<type 'datetime.datetime'>
# when you retrived data from mongo db, it will give you native datime object, too:
>>> python_date_object_retrive_from_mongo = python_date_object_for_insert_mongo
# so we use strftime to transfer back from datetime to string
>>> transfer_to_original_format = datetime.datetime.strftime(python_date_object_retrive_from_mongo, '%d.%m.%Y')
# check it out
>>> print transfer_to_original_format
22.12.2015
>>> print type(transfer_to_original_format)
<type 'str'>
>>>
我才意識到,我們可以存儲Python的原生型蒙戈。非常感謝你這麼好的解釋。 –