繁体   English   中英

python UTC时间减去5分钟

[英]python utc time minus 5 minutes

如何在 Python 中将时间四舍五入 5 分钟?

我有这个脚本,但我认为这可以更容易,而且整个小时的计算都出错了。 当它是 22:03 时,它返回 21:95 而不是 21:55。

import datetime
from datetime import date
import time

utc_datetime = datetime.datetime.utcnow()
jaar = date.today().year
maand = time.strftime("%m")
dag = time.strftime("%d")
uurutc = utc_datetime.strftime("%H")
autc = utc_datetime.strftime("%M")
minuututc = int(5 * round(float(autc)/5)-5)
uur = time.strftime("%H")
a = time.strftime("%M")
minuut = int(5 * round(float(a)/5)-5)

timestamp = ''.join(str(x) for x in [jaar, maand, dag, uurutc, minuututc])

print timestamp

代码实际上应该做什么:

我们的本地时间是 UTC+2,但我只需要 UTC 时间,所以输出必须是 UTC。 其次,时间需要在当前时间之前 5 分钟,然后向下取整。 字符串的输出格式应为:YYYYMMDDHHMM。

例子:

当地时间:12:53 > 输出脚本:10:45

当地时间:17:07 > 输出脚本:15:00

当地时间:08:24 > 输出脚本:06:15

谁能帮我解决这个问题?

谢谢!

使用datetime.timedelta

from datetime import datetime, timedelta
now = datetime.utcnow()
rounded = now - timedelta(minutes=now.minute % 5 + 5,
                          seconds=now.second,
                          microseconds=now.microsecond)
print rounded
# -> 2014-04-12 00:05:00

您可以使用d = d.replace(minute=n*(d.minute // n))向下舍入为n分钟:

>>> d = datetime(2014, 4, 12, 0, 7); print(d.replace(minute=5*(d.minute // 5)))
2014-04-12 00:05:00
>>> n = 15
>>> d = datetime(2014, 4, 12, 10, 53); print(d.replace(minute=n*(d.minute//n)))
2014-04-12 10:45:00
>>> d = datetime(2014, 4, 12, 15, 7); print(d.replace(minute=n*(d.minute//n)))
2014-04-12 15:00:00
>>> d = datetime(2014, 4, 12, 6, 24); print(d.replace(minute=n*(d.minute//n)))
2014-04-12 06:15:00
import datetime
time = (datetime.datetime.utcnow() - datetime.timedelta(minutes=5)).strftime('%Y-%m-%dT%H:%M:%SZ')
print(time)

根据上面的评论,使用 timedelta 类:

import datetime

now = datetime.datetime.now()
five_mins = datetime.timedelta(minutes=5)

five_mins_ago = now - five_mins

print five_mins_ago

编辑:其他答案更好,因为它涵盖了四舍五入

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM