Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

timedelta convert to time or int and store it in GAE (python) datastore

It looks like this has been covered somewhat in other questions, but I'm still fairly confused on how to actually do this. My lack of experience isn't helping much with that.

I have two DateTimeProperties - StartTime and EndTime. I'm subtracting StartTime from EndTime to get the Duration. From my previous question (thank you to all that answered!) it looks like this operation is producing a timedelta.

There doesn't seem to be an easy way to store timedelta directly in the GAE datastore, so this means I need to convert it either to an int in milliseconds, to a float in seconds or to time.

I will need to do other calculations on this later as well, such as figuring out avg. duration. Based on that, int seems to make the most sense to me right now.

What's the best way to do this or is there a tutorial I can play with?

Thank you!

like image 349
Sologoub Avatar asked Dec 13 '22 23:12

Sologoub


1 Answers

To make this as easy as possible to work with, there's two steps: Converting the timedelta to an int or a float, and storing it in the datastore. First things first, converting a timedelta to a microtime:

def timedelta_to_microtime(td):
  return td.microseconds + (td.seconds + td.days * 86400) * 1000000

You don't have to do the conversion yourself, though - you can define a custom datastore property, which will allow you to store timedeltas directly to your model:

class TimeDeltaProperty(db.Property):
  def get_value_for_datastore(self, model_instance):
    value = self.__get__(model_instance, model_instance.__class__)
    if value is not None:
      return timedelta_to_microtime(value)

  def make_value_from_datastore(self, value):
    if value is not None:
      return datetime.timedelta(microseconds=value)

Now you can use this property like any other:

class MyModel(db.Model):
  td = TimeDeltaProperty(required=True)

entity = MyModel(td=datetime.datetime.now()-some_datetime)
key = entity.put()

entity = db.get(key)
print entity.td
like image 98
Nick Johnson Avatar answered Mar 01 '23 22:03

Nick Johnson