在python中操作DateTime和TimeDelta对象 [英] Manipulating DateTime and TimeDelta objects in python

查看:149
本文介绍了在python中操作DateTime和TimeDelta对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何操纵Datetime和Time delta对象。我正在写一个游戏,其中不同的星球有不同的时标。我想知道如何修改日期时间对象。

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.

例如,如果我有一个日期时间对象-一些过去的日期时间对象,我想知道是否有可能知道6个小时有多少次会变得不同,而剩余的分钟数又是多少?

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?

例如...

now = datetime.now()
then = some datetime object
diff = now - then
num 6 hour blocks = diff / 6 (rounded down)
minutes = diff % 6

谢谢!

推荐答案

timedelta对象在Python 2.7中具有total_seconds方法。因此,您可以使用它来解决。当您从另一个日期时间对象中减去一个日期时间对象时,您会得到一个timedelta对象。

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

这就是您想做的事吗?如果您使用的是旧版本的Python,则可以定义一个函数,该函数的功能与total_seconds方法相同,如下所示:

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

这篇关于在python中操作DateTime和TimeDelta对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆