Kavitha Madhavaraj
Kavitha Madhavaraj

Reputation: 592

How to store and retrieve date as dd/mm/yyyy in MongoDB?

I'm using pandas to convert txt file to csv and few columns of the converted CSV goes into MongoDB with minimum of thousand rows.

One field among them is date in the dd.mm.yyyy format. I want it to be stored in MongoDB in whatever way so that I should be able to make queries based on date (less than / greater than date) and retrieve the records(Mongo Documents) in the same format back as dd.mm.yyyy to python code.

    db.mydata.insert({
     name: 'Bob',
     birth: '12.03.1995',
     language: [ 'English', 'French', 'Mandrin']            
   })

I'm a beginner to python and MongoDB. Please guide me !

Upvotes: 1

Views: 1720

Answers (1)

zxcpoiu
zxcpoiu

Reputation: 316

MongoDB uses BSON to store data, and pymongo will transfer your python datetime object to BSON automatically when save to mongoDB, then you can use filter to query mongoDB.

Note that documents can contain native Python types (like datetime.datetime instances) which will be automatically converted to and from the appropriate BSON types.

So, all you need is to transfer between datetime type and string type back and forth.

Use these two functions, you can check it on official python manual:

8.1.7. strftime() and strptime() Behavior

The document explains which argument/format you should use.

Some example will help you get it better, assume you are using 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'>
>>>

Upvotes: 2

Related Questions