Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python utc time minus 5 minutes

Tags:

python

time

How to round down a time 5 minutes in Python?

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

What the code should actually do:

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.

Example:

local time: 12:53 > output script: 10:45

local time: 17:07 > output script: 15:00

local time: 08:24 > output script: 06:15

Who can help me with this out?

Thank you!

like image 925
user3408380 Avatar asked Apr 29 '26 03:04

user3408380


1 Answers

Use 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
like image 139
Steinar Lima Avatar answered May 03 '26 00:05

Steinar Lima



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!