Reputation: 922
I am wondering how to manipulate Datetime and Time delta objects. I am writing a game where different planets have different timescales. And I was wondering how it might be possible to mod datetime objects.
For example if I have a date time object - some past datetime object I was wondering if it was possible to know how many times 6 hours might into the different and what the remainder in minutes was?
For example...
now = datetime.now()
then = some datetime object
diff = now - then
num 6 hour blocks = diff / 6 (rounded down)
minutes = diff % 6
Thanks!
Upvotes: 2
Views: 6747
Reputation: 25569
timedelta objects have a total_seconds method in Python 2.7. So you could use that to work it out. You get a timedelta object back when you subtract one datetime object from another.
from datetime import timedelta
minutes = 60
hours = 60 * minutes
days = 24 * hours
diff = timedelta(days=6)
days_in_the_past = int(diff.total_seconds() / days)
hours_remainder = diff.total_seconds() % days
hours_in_the_past = int(diff.total_seconds() / hours)
seconds_remainder = diff.total_seconds() % hours
Is that pretty much what you wanted to do? If you are using an older version of Python then you could define a function that did the same thing as the total_seconds method like this:
def total_seconds(timedelta_object):
return timedelta_object.days * 86400 + timedelta_object.seconds
Upvotes: 3
Reputation: 65791
timedelta
objects only have days
, seconds
and microseconds
fields, so I guess for hours and minutes you'll have to use seconds
:
num_blocks = diff.seconds//(6*3600)
minutes = (diff.seconds%(6*3600))//60
Upvotes: 0