Python 中的舍入时间

发布于 2024-11-25 14:04:12 字数 326 浏览 2 评论 0原文

在 Python 中对时间相关类型执行 ah/m/s 舍入操作并控制舍入分辨率的优雅、高效和 Pythonic 方法是什么?

我的猜测是,这需要时间模运算。说明性示例:

  • 20:11:13%(10秒)=> (3秒)
  • 20:11:13%(10分钟)==> (1分13秒)

我能想到的相关时间相关类型:

  • datetime.datetime \ datetime.time
  • struct_time

What would be an elegant, efficient and Pythonic way to perform a h/m/s rounding operation on time related types in Python with control over the rounding resolution?

My guess is that it would require a time modulo operation. Illustrative examples:

  • 20:11:13 % (10 seconds) => (3 seconds)
  • 20:11:13 % (10 minutes) => (1 minutes and 13 seconds)

Relevant time related types I can think of:

  • datetime.datetime \ datetime.time
  • struct_time

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

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

发布评论

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

评论(9

始终不够爱げ你 2024-12-02 14:04:12

怎么样使用datetime.timedeltas:

import time
import datetime as dt

hms=dt.timedelta(hours=20,minutes=11,seconds=13)

resolution=dt.timedelta(seconds=10)
print(dt.timedelta(seconds=hms.seconds%resolution.seconds))
# 0:00:03

resolution=dt.timedelta(minutes=10)
print(dt.timedelta(seconds=hms.seconds%resolution.seconds))
# 0:01:13

How about use datetime.timedeltas:

import time
import datetime as dt

hms=dt.timedelta(hours=20,minutes=11,seconds=13)

resolution=dt.timedelta(seconds=10)
print(dt.timedelta(seconds=hms.seconds%resolution.seconds))
# 0:00:03

resolution=dt.timedelta(minutes=10)
print(dt.timedelta(seconds=hms.seconds%resolution.seconds))
# 0:01:13
等数载,海棠开 2024-12-02 14:04:12

对于 datetime.datetime 舍入,请参阅此函数:
https://stackoverflow.com/a/10854034/1431079

使用示例:

print roundTime(datetime.datetime(2012,12,31,23,44,59,1234),roundTo=60*60)
2013-01-01 00:00:00

For a datetime.datetime rounding, see this function:
https://stackoverflow.com/a/10854034/1431079

Sample of use:

print roundTime(datetime.datetime(2012,12,31,23,44,59,1234),roundTo=60*60)
2013-01-01 00:00:00
酒浓于脸红 2024-12-02 14:04:12

这会将时间数据四舍五入为问题中所要求的分辨率:

import datetime as dt

current = dt.datetime.now()
current_td = dt.timedelta(
    hours = current.hour, 
    minutes = current.minute, 
    seconds = current.second, 
    microseconds = current.microsecond)

# to seconds resolution
to_sec = dt.timedelta(seconds = round(current_td.total_seconds()))
print(dt.datetime.combine(current, dt.time(0)) + to_sec)

# to minute resolution
to_min = dt.timedelta(minutes = round(current_td.total_seconds() / 60))
print(dt.datetime.combine(current, dt.time(0)) + to_min)

# to hour resolution
to_hour = dt.timedelta(hours = round(current_td.total_seconds() / 3600))
print(dt.datetime.combine(current, dt.time(0)) + to_hour)

This will round up time data to a resolution as asked in the question:

import datetime as dt

current = dt.datetime.now()
current_td = dt.timedelta(
    hours = current.hour, 
    minutes = current.minute, 
    seconds = current.second, 
    microseconds = current.microsecond)

# to seconds resolution
to_sec = dt.timedelta(seconds = round(current_td.total_seconds()))
print(dt.datetime.combine(current, dt.time(0)) + to_sec)

# to minute resolution
to_min = dt.timedelta(minutes = round(current_td.total_seconds() / 60))
print(dt.datetime.combine(current, dt.time(0)) + to_min)

# to hour resolution
to_hour = dt.timedelta(hours = round(current_td.total_seconds() / 3600))
print(dt.datetime.combine(current, dt.time(0)) + to_hour)
俏︾媚 2024-12-02 14:04:12

您可以将两个时间都转换为秒,进行模运算

from datetime import time

def time2seconds(t):
    return t.hour*60*60+t.minute*60+t.second

def seconds2time(t):
    n, seconds = divmod(t, 60)
    hours, minutes = divmod(n, 60)
    return time(hours, minutes, seconds)

def timemod(a, k):
    a = time2seconds(a)
    k = time2seconds(k)
    res = a % k
    return seconds2time(res)

print(timemod(time(20, 11, 13), time(0,0,10)))
print(timemod(time(20, 11, 13), time(0,10,0)))

输出:

00:00:03
00:01:13

You can convert both times to seconds, do the modulo operati

from datetime import time

def time2seconds(t):
    return t.hour*60*60+t.minute*60+t.second

def seconds2time(t):
    n, seconds = divmod(t, 60)
    hours, minutes = divmod(n, 60)
    return time(hours, minutes, seconds)

def timemod(a, k):
    a = time2seconds(a)
    k = time2seconds(k)
    res = a % k
    return seconds2time(res)

print(timemod(time(20, 11, 13), time(0,0,10)))
print(timemod(time(20, 11, 13), time(0,10,0)))

Outputs:

00:00:03
00:01:13
少钕鈤記 2024-12-02 14:04:12

我使用以下代码片段四舍五入到下一小时:

import datetime as dt

tNow  = dt.datetime.now()
# round to the next full hour
tNow -= dt.timedelta(minutes = tNow.minute, seconds = tNow.second, microseconds =  tNow.microsecond)
tNow += dt.timedelta(hours = 1)

I use following code snippet to round to the next hour:

import datetime as dt

tNow  = dt.datetime.now()
# round to the next full hour
tNow -= dt.timedelta(minutes = tNow.minute, seconds = tNow.second, microseconds =  tNow.microsecond)
tNow += dt.timedelta(hours = 1)
落日海湾 2024-12-02 14:04:12

我想我会以秒为单位转换时间,并从那时起使用标准模运算。

20:11:13 = 20*3600 + 11*60 + 13 = 72673 秒

72673 % 10 = 3

72673 % (10*60) = 73< /code>

这是我能想到的最简单的解决方案。

I think I'd convert the time in seconds, and use standard modulo operation from that point.

20:11:13 = 20*3600 + 11*60 + 13 = 72673 seconds

72673 % 10 = 3

72673 % (10*60) = 73

This is the easiest solution I can think about.

故事↓在人 2024-12-02 14:04:12

这是每小时舍入的有损*版本:

dt = datetime.datetime
now = dt.utcnow()
rounded = dt.utcfromtimestamp(round(now.timestamp() / 3600, 0) * 3600)

相同的原理可以应用于不同的时间跨度。

*上述方法假设使用 UTC,因为任何时区信息在转换为时间戳时都会被破坏。

Here is a lossy* version of hourly rounding:

dt = datetime.datetime
now = dt.utcnow()
rounded = dt.utcfromtimestamp(round(now.timestamp() / 3600, 0) * 3600)

Same principle can be applied to different time spans.

*The above method assumes UTC is used, as any timezone information will be destroyed in conversion to timestamp.

挖鼻大婶 2024-12-02 14:04:12
import pandas as pd
import datetime as dt
import re
>>> re.sub('000

非常丑陋,但如果只是一次性使用,则避免定义函数。

,'', str( pd.Series( dt.datetime.now()).round('ms')[0] ) ) Out[38]: '2024-07-24 10:25:05.816'

非常丑陋,但如果只是一次性使用,则避免定义函数。

import pandas as pd
import datetime as dt
import re
>>> re.sub('000

Very ugly, but avoids defining a function if the usage is just a one-off.

,'', str( pd.Series( dt.datetime.now()).round('ms')[0] ) ) Out[38]: '2024-07-24 10:25:05.816'

Very ugly, but avoids defining a function if the usage is just a one-off.

べ繥欢鉨o。 2024-12-02 14:04:12

您还可以尝试 pandas.Timestamp.round

import datetime
import pandas as pd

t = datetime.datetime(2012,12,31,23,44,59,1234)
print(pd.to_datetime(t).round('1min'))
% Timestamp('2012-12-31 23:45:00')

如果要将结果更改回日期时间格式,可以执行以下操作:

pd.to_datetime(t).round('1min').to_pydatetime()
% datetime.datetime(2012, 12, 31, 23, 45)

You could also try pandas.Timestamp.round:

import datetime
import pandas as pd

t = datetime.datetime(2012,12,31,23,44,59,1234)
print(pd.to_datetime(t).round('1min'))
% Timestamp('2012-12-31 23:45:00')

You can perform the following if you want to change the result back to datetime format:

pd.to_datetime(t).round('1min').to_pydatetime()
% datetime.datetime(2012, 12, 31, 23, 45)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文