python utc 时间减去 5 分钟

标签 python time

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

相关文章:

python - 值错误: could not convert string to float: 'False' in python

python - 在Pygame中根据FPS制作时间延迟

java - 如何独立于系统时间获取时间增量?

c - 如何仅计算当前进程(包括所有线程)的时钟周期

bash - 如何在 bash 中添加两个时间输出

python - 是否可以使用 csv.DictReader 保持列顺序?

php - PHP 中 Python 的 dir 函数的等价物

python 算法以 pythonic 方式完成?

javascript - 为什么这个阶乘查找算法的运行时复杂度不是 O(n!)?

python - 将数据框中两列的日期/时间合并为一列