28

I'm trying to get the timestamp from an ObjectID, but Mongo keeps giving me this error. Am I missing an import? What's the best way to convert the timestamp to a standard date format?

video['date'] = video['_id'].getTimeStamp()
zakdances
  • 22,285
  • 32
  • 102
  • 173
  • FYI, this site demos converting ObjectIds to timestamps: https://steveridout.github.io/mongo-object-time/ – Nikhil VJ Aug 11 '20 at 13:55

3 Answers3

64

Where'd you see getTimeStamp() as a method?

According to the docs it should just be:

video['date'] = video['_id'].generation_time
Rafa Viotti
  • 9,998
  • 4
  • 42
  • 62
Eric Hulser
  • 3,912
  • 21
  • 20
  • 1
    It's provided in Mongoose (http://stackoverflow.com/questions/13350642/how-to-get-creation-date-from-object-id-in-mongoose) – franzlorenzon Mar 18 '13 at 10:46
  • 2
    This seems to be a pretty old post, but I figure I'll reply anyway since someone upvoted the above comment (@franzlorenzon). Mongoose is a JAVASCRIPT library, and this question pertains to Python. That is why `getTimeStamp()` does not work in this case. – Olivercodes Aug 10 '16 at 19:24
10

this answer is python and Django based.

Before using generation_time be aware that generation_time will be converted to UTC(Universal Time) which might be ahead or behind depending on your current timezone, so you might see a difference in time if you are using your Local Time in your project settings to save timestamps on your objects. For me, there is a difference of 5.5 hours. So adjust the time according to your timezone.

Example: For ObjectId('5c51aca67c76124020edbbaf') the actuall creation time of this object was datetime.datetime(2019, 1, 30, 19, 24, 28, 73000) but when i geneted its time using generation_time it is 5.5 hours behind.

In [10]: from bson import ObjectId

In [11]: ObjectId('5c51aca67c76124020edbbaf').generation_time
Out[11]: datetime.datetime(2019, 1, 30, 13, 54, 46, tzinfo=<bson.tz_util.FixedOffset object at 0x102461128>)
Vishal Singh
  • 6,014
  • 2
  • 17
  • 33
0

Since we get the time in UTC from the object_id of our document, to convert to your local time what you can do is ...

document['_id'].generation_time  #(gives the generation/creation time of the object id in UTC.)
utc=document['_id'].generation_time
hours_added = datetime.timedelta(hours = 4)`  #(Suppose utc+4 is my local time.)
local_time=utc+hours_added  
Amal Sunil
  • 133
  • 2
  • That's true, but is there a more elegant way to do it? – Johnny Mar 17 '21 at 05:50
  • -1 for that suggestion. You should never do something like that. What if you have summer time and winter time. It will not be right. You should convert using i.e. `astimezone`. Few examples here: [https://stackoverflow.com/questions/4770297/convert-utc-datetime-string-to-local-datetime](https://stackoverflow.com/questions/4770297/convert-utc-datetime-string-to-local-datetime) – Wojciech Jakubas Oct 01 '21 at 17:46