如何在 Python 中将时间四舍五入 5 分钟?
How to round down a time 5 minutes in Python?
我有这个脚本,但我认为这可以更容易,而且整个小时的计算都出错了.当它是 22:03 时,它返回 21:95 而不是 21:55.
I have this script, but i think this can be easyer, and the full hours the calculation goes wrong. When its 22:03 it returns 21:95 instead of 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.
Our local time is UTC+2, but i only need the UTC time, so the output must be in UTC. Second, the time needs to be 5 min before current time and then round down. The output format of the string should be: YYYYMMDDHHMM.
示例:
当地时间:12:53 > 输出脚本:10:45
local time: 12:53 > output script: 10:45
当地时间:17:07 > 输出脚本:15:00
local time: 17:07 > output script: 15:00
当地时间:08:24 > 输出脚本:06:15
local time: 08:24 > output script: 06:15
谁能帮我解决这个问题?
Who can help me with this out?
谢谢!
推荐答案使用 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分钟
发布评论