gpt4 book ai didi

python utc 时间减去 5 分钟

转载 作者:太空宇宙 更新时间:2023-11-04 08:10:41 32 4
gpt4 key购买 nike

如何在 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

关于python utc 时间减去 5 分钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23024450/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com