python UTC时间减去5分钟

编程入门 行业动态 更新时间:2024-10-28 12:27:24
本文介绍了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分钟

本文发布于:2023-06-05 21:04:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/527639.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时间   python   UTC

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!