Kishore
Kishore

Reputation: 11

Convert MongoDB time to epoch time - Python

I have a mongodb time as objectid("5217a543dd99a6d9e0f74702").

How to convert it to epoch time in Python. (UTC timezone and also EST timezone)

Upvotes: 1

Views: 3362

Answers (2)

A. Jesse Jiryu Davis
A. Jesse Jiryu Davis

Reputation: 24017

ObjectId.generation_time gives you the time the ObjectId was generated, in UTC:

>>> from bson import ObjectId
>>> ObjectId("5217a543dd99a6d9e0f74702").generation_time
datetime.datetime(2013, 8, 23, 18, 9, 7, tzinfo=<bson.tz_util.FixedOffset object at 0x102920c90>)

The documentation is here.

To convert to Eastern Time, install pytz and:

>>> import pytz
>>> ny = pytz.timezone('America/New_York')
>>> gt = ObjectId("5217a543dd99a6d9e0f74702").generation_time
>>> ny.normalize(gt.astimezone(ny))
datetime.datetime(2013, 8, 23, 14, 9, 7, tzinfo=<DstTzInfo 'America/New_York' EDT-1 day, 20:00:00 DST>)

Upvotes: 2

Anand Jayabalan
Anand Jayabalan

Reputation: 12944

You can use the ObjectId.getTimestamp() method to get the timestamp portion of the objectid as Date.

Once you have the Date object you can call any of the Date methods to get what you want. In the shell, you could just hit TAB to get the list of all methods that are permitted:

> var myid = new ObjectId()
> myid
ObjectId("5331ba8163083f9b26efb5b3")
> var mytime = myid.getTimestamp()
> mytime
ISODate("2014-03-25T17:18:57Z")
> mytime.<TAB>
mytime.constructor            mytime.getUTCFullYear(
mytime.getDate(               mytime.getUTCHours(
mytime.getDay(                mytime.getUTCMilliseconds(
mytime.getFullYear(           mytime.getUTCMinutes(
mytime.getHours(              mytime.getUTCMonth(
mytime.getMilliseconds(       mytime.getUTCSeconds(
mytime.getMinutes(            mytime.getYear(
mytime.getMonth(              mytime.hasOwnProperty(
mytime.getSeconds(            mytime.propertyIsEnumerable(
mytime.getTime(               mytime.setDate(
mytime.getTimezoneOffset(     mytime.setFullYear(
mytime.getUTCDate(            mytime.setHours(
mytime.getUTCDay(             mytime.setMilliseconds(

Note: I'm not familiar with Python, but the same concepts would apply

Upvotes: 0

Related Questions