fansonly
fansonly

Reputation: 1200

PyMongo storing ISODate without milliseconds when milliseconds are zero

After running a script today I noticed that the created_on time for some of my documents looked like:

ISODate("2013-05-30T17:46:55Z") no millis

ISODate("2013-05-30T21:08:02.261Z") millis for most rows

WHen parsing the former..my code expected the millis to be there:

    dt = datetime.strptime(dt, '%Y-%m-%d %H:%M:%S.%f')
    File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime (data_string, format))
    ValueError: time data '2013-05-30 17:46:55' does not match format '%Y-%m-%d %H:%M:%S.%f'

How can I make sure that ISODate("2013-05-30T17:46:55.0000Z") gets stored in the document so that the parser can be consistent?

Upvotes: 1

Views: 2530

Answers (1)

A. Jesse Jiryu Davis
A. Jesse Jiryu Davis

Reputation: 24017

One option is, store datetimes as datetimes in MongoDB, not as strings. Then you won't need to parse them with strptime in order to get datetimes back out and millis are no problem:

>>> dt = datetime.now()
>>> str(dt)
'2013-06-03 13:04:22.976182'
>>> db.collection.insert({'now': dt})
ObjectId('51accca7ca1ce90a4277ac20')
>>> dt = datetime.now().replace(microsecond=0)
>>> str(dt)
'2013-06-03 13:04:47'
>>> db.collection.insert({'now': dt})
ObjectId('51acccb6ca1ce90a4277ac21')
>>> pprint.pprint(list(db.collection.find({}, {'now': True, '_id': False})))
[{u'now': datetime.datetime(2013, 6, 3, 13, 4, 22, 976000)},
 {u'now': datetime.datetime(2013, 6, 3, 13, 4, 47)}]

If it's too late for you to change how you store datetimes, you can pip install python-dateutil and do:

>>> from dateutil.parser import parse
>>> parse('2013-06-03 13:04:22.976182')
datetime.datetime(2013, 6, 3, 13, 4, 22, 976182)
>>> parse('2013-06-03 13:04:22')
datetime.datetime(2013, 6, 3, 13, 4, 22)

Upvotes: 2

Related Questions