将 timedelta 转换为天、小时和分钟

发布于 2024-08-19 08:47:51 字数 331 浏览 4 评论 0原文

我有一个时间增量。我想要其中的天数、小时数和分钟数 - 无论是作为元组还是字典......我并不大惊小怪。

多年来我一定用十几种语言做过十几次这样的事情,但 Python 通常对所有事情都有一个简单的答案,所以我想我应该在这里问一下,然后再搞出一些简单得令人作呕(但又冗长)的数学。

福兹先生提出了一个很好的观点。

我正在处理“列表”(有点像 eBay 列表),其中每个列表都有一个持续时间。我正在尝试通过执行 when_added +uration - now 来查找剩余时间。

我说的对吗?这不能解释 DST?如果不是,加/减一个小时最简单的方法是什么?

I've got a timedelta. I want the days, hours and minutes from that - either as a tuple or a dictionary... I'm not fussed.

I must have done this a dozen times in a dozen languages over the years but Python usually has a simple answer to everything so I thought I'd ask here before busting out some nauseatingly simple (yet verbose) mathematics.

Mr Fooz raises a good point.

I'm dealing with "listings" (a bit like ebay listings) where each one has a duration. I'm trying to find the time left by doing when_added + duration - now

Am I right in saying that wouldn't account for DST? If not, what's the simplest way to add/subtract an hour?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

苦笑流年记忆 2024-08-26 08:47:51

如果您有一个 datetime.timedeltatdtd.days 已经为您提供了您想要的“天”。 timedelta 值将一天的一小部分保留为秒(而不是直接的小时或分钟),因此您确实必须执行“令人作呕的简单数学”,例如:

def days_hours_minutes(td):
    return td.days, td.seconds//3600, (td.seconds//60)%60

If you have a datetime.timedelta value td, td.days already gives you the "days" you want. timedelta values keep fraction-of-day as seconds (not directly hours or minutes) so you'll indeed have to perform "nauseatingly simple mathematics", e.g.:

def days_hours_minutes(td):
    return td.days, td.seconds//3600, (td.seconds//60)%60
遗弃M 2024-08-26 08:47:51

这是更紧凑一点,你可以在两行中得到小时、分钟和秒。

days = td.days
hours, remainder = divmod(td.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
# If you want to take into account fractions of a second
seconds += td.microseconds / 1e6

This is a bit more compact, you get the hours, minutes and seconds in two lines.

days = td.days
hours, remainder = divmod(td.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
# If you want to take into account fractions of a second
seconds += td.microseconds / 1e6
空城仅有旧梦在 2024-08-26 08:47:51
days, hours, minutes = td.days, td.seconds // 3600, td.seconds // 60 % 60

至于 DST,我认为最好的办法是将两个 datetime 对象都转换为秒。这样系统就会为您计算 DST。

>>> m13 = datetime(2010, 3, 13, 8, 0, 0)  # 2010 March 13 8:00 AM
>>> m14 = datetime(2010, 3, 14, 8, 0, 0)  # DST starts on this day, in my time zone
>>> mktime(m14.timetuple()) - mktime(m13.timetuple())     # difference in seconds
82800.0
>>> _/3600                                                # convert to hours
23.0
days, hours, minutes = td.days, td.seconds // 3600, td.seconds // 60 % 60

As for DST, I think the best thing is to convert both datetime objects to seconds. This way the system calculates DST for you.

>>> m13 = datetime(2010, 3, 13, 8, 0, 0)  # 2010 March 13 8:00 AM
>>> m14 = datetime(2010, 3, 14, 8, 0, 0)  # DST starts on this day, in my time zone
>>> mktime(m14.timetuple()) - mktime(m13.timetuple())     # difference in seconds
82800.0
>>> _/3600                                                # convert to hours
23.0
鯉魚旗 2024-08-26 08:47:51

对于所有正在寻找实现的人:

以上帖子与 datetime.timedelta 相关,遗憾的是它没有小时和秒的属性。到目前为止还没有提到有一个包包含这些。您可以在这里找到它:

示例 - 计算:

>>> import timedelta

>>> td = timedelta.Timedelta(days=2, hours=2)

# init from datetime.timedelta
>>> td = timedelta.Timedelta(datetime1 - datetime2)

示例 - 属性:

>>> td = timedelta.Timedelta(days=2, hours=2)
>>> td.total.seconds
180000
>>> td.total.minutes
3000
>>> td.total.hours
50
>>> td.total.days
2

我希望这可以帮助某人......

For all coming along and searching for an implementation:

The above posts are related to datetime.timedelta, which is sadly not having properties for hours and seconds. So far it was not mentioned, that there is a package, which is having these. You can find it here:

Example - Calculation:

>>> import timedelta

>>> td = timedelta.Timedelta(days=2, hours=2)

# init from datetime.timedelta
>>> td = timedelta.Timedelta(datetime1 - datetime2)

Example - Properties:

>>> td = timedelta.Timedelta(days=2, hours=2)
>>> td.total.seconds
180000
>>> td.total.minutes
3000
>>> td.total.hours
50
>>> td.total.days
2

I hope this could help someone...

み青杉依旧 2024-08-26 08:47:51

我不明白

days, hours, minutes = td.days, td.seconds // 3600, td.seconds // 60 % 60

这个怎么样

days, hours, minutes = td.days, td.seconds // 3600, td.seconds % 3600 / 60.0

你得到一分钟的分钟和秒作为浮动。

I don't understand

days, hours, minutes = td.days, td.seconds // 3600, td.seconds // 60 % 60

how about this

days, hours, minutes = td.days, td.seconds // 3600, td.seconds % 3600 / 60.0

You get minutes and seconds of a minute as a float.

方圜几里 2024-08-26 08:47:51

我使用了以下内容:

delta = timedelta()
totalMinute, second = divmod(delta.seconds, 60)
hour, minute = divmod(totalMinute, 60)
print(f"{hour}h{minute:02}m{second:02}s")

I used the following:

delta = timedelta()
totalMinute, second = divmod(delta.seconds, 60)
hour, minute = divmod(totalMinute, 60)
print(f"{hour}h{minute:02}m{second:02}s")
怎言笑 2024-08-26 08:47:51

这是我整理的一个小函数,可以精确到微秒:

def tdToDict(td:datetime.timedelta) -> dict:
    def __t(t, n):
        if t < n: return (t, 0)
        v = t//n
        return (t -  (v * n), v)
    (s, h) = __t(td.seconds, 3600)
    (s, m) = __t(s, 60)    
    (micS, milS) = __t(td.microseconds, 1000)

    return {
         'days': td.days
        ,'hours': h
        ,'minutes': m
        ,'seconds': s
        ,'milliseconds': milS
        ,'microseconds': micS
    }

这是一个返回元组的版本:

# usage: (_d, _h, _m, _s, _mils, _mics) = tdTuple(td)
def tdTuple(td:datetime.timedelta) -> tuple:
    def _t(t, n):
        if t < n: return (t, 0)
        v = t//n
        return (t -  (v * n), v)
    (s, h) = _t(td.seconds, 3600)
    (s, m) = _t(s, 60)    
    (mics, mils) = _t(td.microseconds, 1000)
    return (td.days, h, m, s, mics, mils)

Here is a little function I put together to do this right down to microseconds:

def tdToDict(td:datetime.timedelta) -> dict:
    def __t(t, n):
        if t < n: return (t, 0)
        v = t//n
        return (t -  (v * n), v)
    (s, h) = __t(td.seconds, 3600)
    (s, m) = __t(s, 60)    
    (micS, milS) = __t(td.microseconds, 1000)

    return {
         'days': td.days
        ,'hours': h
        ,'minutes': m
        ,'seconds': s
        ,'milliseconds': milS
        ,'microseconds': micS
    }

Here is a version that returns a tuple:

# usage: (_d, _h, _m, _s, _mils, _mics) = tdTuple(td)
def tdTuple(td:datetime.timedelta) -> tuple:
    def _t(t, n):
        if t < n: return (t, 0)
        v = t//n
        return (t -  (v * n), v)
    (s, h) = _t(td.seconds, 3600)
    (s, m) = _t(s, 60)    
    (mics, mils) = _t(td.microseconds, 1000)
    return (td.days, h, m, s, mics, mils)
杀お生予夺 2024-08-26 08:47:51

虽然pandas.Timedelta没有直接提供这些属性,但它确实提供了一个名为total_seconds的方法,基于该方法可以轻松导出天、小时和分钟:

import pandas as pd
td = pd.Timedelta("2 days 12:30:00")
minutes = td.total_seconds()/60
hours = minutes/60
days = hours/ 24
print(minutes, hours, days)

While pandas.Timedelta does not provide these attributes directly, it indeed provide a method called total_seconds, based on which days, hours, and minutes can be easily derived:

import pandas as pd
td = pd.Timedelta("2 days 12:30:00")
minutes = td.total_seconds()/60
hours = minutes/60
days = hours/ 24
print(minutes, hours, days)
仙女山的月亮 2024-08-26 08:47:51

如果你使用 python datetime 包,你也可以像下面这样编码:

import datetime
tap_in = datetime.datetime.strptime("04:12", "%H:%M")
tap_out = datetime.datetime.strptime("18:20", "%H:%M")
num_of_hour = (tap_out - tap_in).total_seconds()/3600
num_of_hour # 14.133333333333333

While if you are using python datetime package, you can also code like below:

import datetime
tap_in = datetime.datetime.strptime("04:12", "%H:%M")
tap_out = datetime.datetime.strptime("18:20", "%H:%M")
num_of_hour = (tap_out - tap_in).total_seconds()/3600
num_of_hour # 14.133333333333333
一个人练习一个人 2024-08-26 08:47:51

我发现最简单的方法是使用 str(timedelta)。它将返回一个格式类似于 3 days, 21:06:40.001000 的字符串,您可以使用简单的字符串操作或正则表达式来解析小时和分钟。

I found the easiest way is using str(timedelta). It will return a sting formatted like 3 days, 21:06:40.001000, and you can parse hours and minutes using simple string operations or regular expression.

梦里南柯 2024-08-26 08:47:51
timedelta = pd.Timestamp("today") - pd.Timestamp("2022-01-01")
print(timedelta.components)
print(timedelta.components.days)
print(timedelta.components.seconds)

将返回类似以下内容:

Components(days=281, hours=2, minutes=24, seconds=3, milliseconds=72, microseconds=493, nanoseconds=0) 
281
3
timedelta = pd.Timestamp("today") - pd.Timestamp("2022-01-01")
print(timedelta.components)
print(timedelta.components.days)
print(timedelta.components.seconds)

will return something like:

Components(days=281, hours=2, minutes=24, seconds=3, milliseconds=72, microseconds=493, nanoseconds=0) 
281
3
甜心小果奶 2024-08-26 08:47:51

这是另一种可能的方法,尽管比已经提到的方法稍微冗长一些。对于这种情况,这可能不是最好的方法,但能够方便地获取未存储在对象中的特定单位的持续时间(周、小时、分钟、毫秒),并且无需记住或计算转换系数。

from datetime import timedelta
one_hour = timedelta(hours=1)
one_minute = timedelta(minutes=1)
print(one_hour/one_minute)  # Yields 60.0

我有一个时间增量。我想要其中的天数、小时数和分钟数 - 无论是作为元组还是字典......我并不大惊小怪。

in_time_delta = timedelta(days=2, hours=18, minutes=30)
td_d = timedelta(days=1)
td_h = timedelta(hours=1)
td_m = timedelta(minutes=1)
dmh_list = [in_time_delta.days,
            (in_time_delta%td_d)//td_h,
            (in_time_delta%td_h)//td_m]

应该将 [2, 18, 30] 分配给 dmh_list

This is another possible approach, though a bit wordier than those already mentioned. It maybe isn't the best approach for this scenario but it is handy to be able to obtain your time duration in a specific unit that isn't stored within the object (weeks, hours, minutes, milliseconds) and without having to remember or calculate conversion factors.

from datetime import timedelta
one_hour = timedelta(hours=1)
one_minute = timedelta(minutes=1)
print(one_hour/one_minute)  # Yields 60.0

I've got a timedelta. I want the days, hours and minutes from that - either as a tuple or a dictionary... I'm not fussed.

in_time_delta = timedelta(days=2, hours=18, minutes=30)
td_d = timedelta(days=1)
td_h = timedelta(hours=1)
td_m = timedelta(minutes=1)
dmh_list = [in_time_delta.days,
            (in_time_delta%td_d)//td_h,
            (in_time_delta%td_h)//td_m]

Which should assign [2, 18, 30] to dmh_list

七色彩虹 2024-08-26 08:47:51

如果使用pandas(至少版本>1.0),Timedelta类有一个components属性,它返回一个包含所有字段的命名元组布置。

例如

import pandas as pd
delta = pd.Timestamp("today") - pd.Timestamp("2022-03-01")
print(delta.components)

If using pandas (at least version >1.0), the Timedelta class has a components attribute that returns a named tuple with all the fields nicely laid out.

e.g.

import pandas as pd
delta = pd.Timestamp("today") - pd.Timestamp("2022-03-01")
print(delta.components)
紫南 2024-08-26 08:47:51

timedeltas 有一个属性..您可以轻松地自己转换它们。

timedeltas have a days and seconds attribute .. you can convert them yourself with ease.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文