python UTC时间减去5分钟 [英] python utc time minus 5 minutes

查看:60
本文介绍了python UTC时间减去5分钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 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分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆