I have a variable holding information about time (not current time) in the YYYYMMDDHHMMSS format.
I have a starting point and a finish point. Lets say '20210419000100' and '20210419130100'. Thats 13 hours from start to finish.
I want to save a string of this time for every 15 mins. ie we start at '20210419000100' and 15 mins later it will be '20210419001600'.
Obviously its not always +1500. I know its a long shot, but is there a tool for that or how could i do that in a generic way that would work with any starting point I would choose? It could be done only in HHMMSS format if its easier but if possible I would like the year/month/day to change, too.
I am more interested in a python solution.
python-dateutil to the rescue!
from dateutil import parser, relativedelta
START_DATE = '20210419000100'
END_DATE = '20210419130100'
start = parser.parse(START_DATE)
end = parser.parse(END_DATE)
while start < end:
print(start.strftime("%Y%m%d%H%M%S"))
start += relativedelta.relativedelta(minutes=15)
No need to install other dependencies, you can use python's standard datetime module
from datetime import datetime, timedelta
time_str = '20210419000100'
time_obj = datetime.strptime(time_str, '%Y%m%d%H%M%S')
print(time_obj)
# 2021-04-19 00:01:00
# If you want to add hours or minutes
def seconds(h = 0, m = 0, s = 0):
return h * 3600 + m * 60 + s
time_obj += timedelta(0, seconds(m=15)) # days, seconds
print(time_obj)
# 2021-04-19 00:16:00
# In case you want to convert it back
new_time_str = time_obj.strftime("%Y%m%d%H%M%S")
print(new_time_str)
# 20210419001600
Related
I'm trying to figure out a way to take two times from the same day and figure out the difference between them. So far shown in the code below I have converted both of the given times into Int Vars and split the strings to retrieve the information. This works well but when the clock in values minute is higher than the clock out value it proceeds to give a negative value in minute slot of the output.
My current code is:
from datetime import datetime
now = datetime.now()
clocked_in = now.strftime("%H:%M")
clocked_out = '18:10'
def calc_total_hours(clockedin, clockedout):
in_hh, in_mm = map(int, clockedin.split(':'))
out_hh, out_mm = map(int, clockedout.split(':'))
hours = out_hh - in_hh
mins = out_mm - in_mm
return f"{hours}:{mins}"
print(calc_total_hours(clocked_in, clocked_out))
if the clocked in value is 12:30 and the clocked out value is 18:10
the output is:
6:-20
the output needs to be converted back into a stand time format when everything is done H:M:S
Thanks for you assistance and sorry for the lack of quality code. Im still learning! :D
First, in order to fix your code, you need to convert both time to minutes, compute the difference and then convert it back to hours and minutes:
clocked_in = '12:30'
clocked_out = '18:10'
def calc_total_hours(clockedin, clockedout):
in_hh, in_mm = map(int, clockedin.split(':'))
out_hh, out_mm = map(int, clockedout.split(':'))
diff = (in_hh * 60 + in_mm) - (out_hh * 60 + out_mm)
hours, mins = divmod(abs(diff) ,60)
return f"{hours}:{mins}"
print(calc_total_hours(clocked_in, clocked_out))
# 5: 40
Better way to implement the time difference:
import time
import datetime
t1 = datetime.datetime.now()
time.sleep(5)
t2 = datetime.datetime.now()
diff = t2 - t1
print(str(diff))
Output:
#h:mm:ss
0:00:05.013823
Probably the most reliable way is to represent the times a datetime objects, and then take one from the other which will give you a timedelta.
from datetime import datetime
clock_in = datetime.now()
clock_out = clock_in.replace(hour=18, minute=10)
seconds_diff = abs((clock_out - clock_in).total_seconds())
hours, minutes = seconds_diff // 3600, (seconds_diff // 60) % 60
print(f"{hours}:{minutes}")
I am trying to get get the time delta i minutes from two different time values.
time1 = 2020-11-28T10:31:12Z
time2 = 2020-11-28T09:10:23.203+0000
Then i will make i condition: if time difference is bigger then x minutes, run code...
Anyone have a solution for that.
I have tried using datetime.datetime.strptime() but cant get them on same format.
Thanks
Using date parser to let it figure out the date format
Code
from dateutil.parser import parse
def time_difference(time1, time2):
# Parse strings into datetime objects
dt1 = parse(time1)
dt2 = parse(time2)
# Get timedelta object
c = dt1 - dt2
# Difference in minutes
return (c.total_seconds()/60)
Test
time1 = "2020-11-28T10:31:12Z"
time2 = "2020-11-28T09:10:23.203+0000"
print(time_difference(time1, time2))
# Output: 80.81328333333333
well assuming you don't need split seconds you could do something like that:
time1 = '2020-11-28T10:31:12Z'
time2 = '2020-11-28T09:10:23.203+0000'
import time
import datetime
def get_timestamp(time_str):
time_splited = time_str.split('T')
time_str_formatted = ' '.join([time_splited[0],time_splited[1][:8]])
return time.mktime(datetime.datetime.strptime(time_str_formatted,"%Y-%m-%d %H:%M:%S").timetuple())
print(get_timestamp(time1))
print(get_timestamp(time2))
reformatting both times to the same time format.
then your condition would look like:
if abs(get_timestamp(time1) -get_timestamp(time2) ) > x*60:
do_something(....)
The times are not uniform so you will have to make them the same to use strptime. For accuracy I prefer to convert to seconds then you can also at a later stage compare seconds, minutes or hours if you needed to.
import datetime
time1 = '2020-11-28T10:31:12Z'
time2 = '2020-11-28T09:10:23.203+0000'
def minutes_diff():
#Make the times uniform so you can then use strptime
date_time1 = datetime.datetime.strptime(time1[:-1], "%Y-%m-%dT%H:%M:%S")
date_time2 = datetime.datetime.strptime(time2[:-9], "%Y-%m-%dT%H:%M:%S")
#Convert to seconds for accuracy
a_timedelta = date_time1 - datetime.datetime(1900, 1, 1)
b_timedelta = date_time2 - datetime.datetime(1900, 1, 1)
seconds_time_a = a_timedelta.total_seconds()
seconds_time_b = b_timedelta.total_seconds()
#Take one from each other for minutes
time_in_minutes = (seconds_time_a - seconds_time_b) / 60
#Then decide what to do with it
if time_in_minutes < 60: # 1 hour
print('Less than an hours do something')
else:
print('More than an hour do nothing')
minutes_diff()
DARRYL, JOHNNY and MARCIN, thanks for your solutions, problem solved!!
Andy
I need to check how many seconds are lef to the nearest HH:MM time in Python (in 24 hour format). For example, now is 10:00 - I need to check 16:30 same day.
If its 18:00 I need to check secods left to the 16:30 next day end so on.
You probably want to use the datetime module, timeldelta is your friend here:
import datetime
def cal_delta_to(hour, minute):
now = datetime.datetime.now()
target = datetime.datetime(*now.timetuple()[0:3], hour=16, minute=30)
if target < now: # if the target is before now, add one day
target += datetime.timedelta(days=1)
diff = now - target
return diff.seconds
Start with simple steps. Programming is usually about breaking down tasks like these into steps.
Get current time. Get next 16:30. Subtract.
# use datetime
from datetime import datetime, timedelta
# get current time
curr = datetime.now()
# create object of nearest 16:30
nearest = datetime(curr.year, curr.month, curr.day, 16, 30)
# stupidly check if it's indeed the next nearest
if nearest < curr:
nearest += timedelta(days=1)
# get diff in seconds
print (nearest - curr).seconds
If your format is ensured, you can easily calculate the seconds of the day:
def seconds_of_day(hhmm):
return int(hhmm[:2])*3600 + int(hhmm[3:])*60
Having done this the comparison is straightforward:
t1 = seconds_of_day('16:30')
t2 = seconds_of_day('10:00')
#t2 = seconds_of_day('18:01')
diff = 86400-t2+t1 if t1<t2 else t1-t2
Use datetime:
import datetime
func = lambda s: datetime.datetime.strptime(s, '%H:%M')
seconds = (func(s2)-func(s1)).seconds
You can always get what you want, even in the special 'next day' cases, like in case1 below;
# case1: now is '09:30', check seconds left to the 09:29 next day
>>> (func('09:29')-func('09:30')).seconds
86340
# case2: now is '09:30', check 10:30 the same day
>>> (func('10:30')-func('09:30')).seconds
3600
I want to control devices (module Raspberry Pi) in a certain time period. I make a PHP web to config time value in database mysql. Then I get time from database to compare with time in system (real time clock). If system time is in between time in mysql => led on.
Here is my table(name: time) in mysql:
start_time stop_time
07:00:00 (Type: time) 08:00:00 (Type:time)
And here is my code control device:
import MySQLdb
import RPi.GPIO as GPIO
from datetime import date
import time
db_local = MySQLdb.connect("localhost","root","root","luan_van")
with db_local:
cur = db_local.cursor(MySQLdb.cursors.DictCursor)
cur.execute("SELECT * FROM time")
rows = cur.fetchall()
start = 0
stop = 0
for row in rows:
start = row['start_time']
stop = row ['stop_time']
tg = strftime("%H:%M:%S", time.localtime())
if( start < tg < stop):
GPIO.output(12, True)
It error "can't compare datetime.timedelta to str".
How can I get system time value format "H:M:S"?
Thank for help.
Your start and stop objects are datetime.timedelta objects; these model time durations, not the time of day. You have two options here:
Produce another timedelta to represent the current time, as a delta since midnight
Convert the start and stop values to actual time-of-day values
You can produce a timedelta for 'now' with:
import datetime
midnight = datetime.datetime.combine(datetime.date.today(), datetime.time.min)
time_since_midnight = datetime.datetime.now() - midnight
then compare that with your start and stop:
if start < time_since_midnight < stop:
In the other direction, converting the start and stop timedeltas to datetime.datetime objects means you need to add them to the midnight object:
import datetime
midnight = datetime.datetime.combine(datetime.date.today(), datetime.time.min)
now = datetime.datetime.now()
if (midnight + start) < now < (midnight + stop):
A variation on the latter could be to just use the .time() components and ignore the date portion, but since you already are basing all dates on 'today' that won't make a difference here.
enter time-1 // eg 01:12
enter time-2 // eg 18:59
calculate: time-1 to time-2 / 12
// i.e time between 01:12 to 18:59 divided by 12
How can it be done in Python. I'm a beginner so I really have no clue where to start.
Edited to add: I don't want a timer. Both time-1 and time-2 are entered by the user manually.
Thanks in advance for your help.
The datetime and timedelta class from the built-in datetime module is what you need.
from datetime import datetime
# Parse the time strings
t1 = datetime.strptime('01:12','%H:%M')
t2 = datetime.strptime('18:59','%H:%M')
# Do the math, the result is a timedelta object
delta = (t2 - t1) / 12
print(delta.seconds)
Simplest and most direct may be something like:
def getime(prom):
"""Prompt for input, return minutes since midnight"""
s = raw_input('Enter time-%s (hh:mm): ' % prom)
sh, sm = s.split(':')
return int(sm) + 60 * int(sh)
time1 = getime('1')
time2 = getime('2')
diff = time2 - time1
print "Difference: %d hours and %d minutes" % (diff//60, diff%60)
E.g., a typical run might be:
$ python ti.py
Enter time-1 (hh:mm): 01:12
Enter time-2 (hh:mm): 18:59
Difference: 17 hours and 47 minutes
Here's a timer for timing code execution. Maybe you can use it for what you want. time() returns the current time in seconds and microseconds since 1970-01-01 00:00:00.
from time import time
t0 = time()
# do stuff that takes time
print time() - t0
Assuming that the user is entering strings like "01:12", you need to convert (as well as validate) those strings into the number of minutes since 00:00 (e.g., "01:12" is 1*60+12, or 72 minutes), then subtract one from the other. You can then convert the difference in minutes back into a string of the form hh:mm.