I have pairs of timestamps from the unix date:
alvas#ubi:~$ date
Wed May 20 01:04:43 CEST 2015
How can I calculate the time difference between the pairs of timestamp?
Note: I don't have the full datetime stamp from $date but only the time in hr:min:sec left in my logfile.
For example, timediff(start, end):
timediff('11:12:10', '19:58:50')
timediff('15:17:09', '03:11:10')
[out]:
31600
42841
[out2]:
8 hrs 46 mins 40 secs (31600 secs)
11 hrs 54 mins 1 secs (42841 secs)
In the case that end < start, treat it as the next day.
I've tried the script below but is there an easier way to do that?
def timediff(start, end):
start_hr, start_min, start_sec = map(float, start.split(':'))
end_hr, end_min, end_sec = map(float, end.split(':'))
if end_hr < start_hr:
end_hr = end_hr + 24
if end_min < start_min:
end_min = end_min + 60
end_hr -= 1
if end_sec < start_sec:
end_sec = end_sec + 60
end_min -= 1
num_hrs = end_hr - start_hr
num_mins = end_min - start_min
num_secs = end_sec - start_sec
total_seconds = 60*60*num_hrs + 60*num_mins+num_secs
total_time = " ".join([str(num_hrs), 'hrs', str(num_mins), 'mins', str(num_secs), 'secs'])
return total_seconds, total_time
print timediff('11:12:10', '19:58:50')
print timediff('15:17:09', '03:11:10')
[out]:
(31600.0, '8.0 hrs 46.0 mins 40.0 secs')
(42841.0, '11.0 hrs 54.0 mins 1.0 secs')
When I tried dateutil.parser.parse:
>>> from dateutil.parser import parse as dtparse
>>> dtparse('19:58:50') - dtparse('11:12:10')
datetime.timedelta(0, 31600)
>>> dtparse('03:11:10') - dtparse('15:17:09')
datetime.timedelta(-1, 42841)
dateutil.parser(pip install python-dateutil) can parse just about anything ... and its timezone aware
from dateutil.parser import parse as dtparse
print dtparse("Wed May 20 01:04:43 CEST 2015") - dtparse("Wed May 20 00:02:43 CEST 2015")
>>> print dtparse("Fri May 22 01:04:43 CEST 2015") - dtparse("Wed May 20 00:02:43
CEST 2015")
2 days, 1:02:00
>>> print dtparse("15:22:36") - dtparse("12:00:45")
3:21:51 # 3 hours, 21 minutes, 51 seconds
here ... this will work if you dont know which timestamp is later ...
def tdiff(t1,t2):
if t1 > t2:t1,t2 = t2,t1
return t2-t1
print tdiff(dtparse('11:12:10'), dtparse('19:58:50'))
if you want to subtract a day in the event the order is wrong try this
def tdiff(t1,t2):
if t1 > t2:t1 - datetime.timedelta(days=1)
return t2-t1
Probably easier to use datetime:
import datetime
def timediff(t1, t2):
d1=datetime.datetime.strptime(t1, "%H:%M:%S")
d2=datetime.datetime.strptime(t2, "%H:%M:%S")
if d2<d1:
d1-=datetime.timedelta(days=1)
return ((d2-d1).total_seconds(), str(d2-d1))
>>> timediff('11:12:10', '19:58:50')
(31600.0, '8:46:40')
>>> timediff('15:17:09', '03:11:10')
(42841.0, '11:54:01')
Related
In python, I am trying to make an alarm system where it converts "x Hours y Minutes and z Seconds" to the x:y:z format
For example:
5 hours 20 minutes 6 seconds
05:20:06
1 hour 25 seconds
01:00:25
This is my code, but it seems scuffed:
time_string = '1 hour and 25 seconds'
correction = time_string.replace('and ', '')
duration = correction.replace(' hour', ':').replace(' minute', ':').replace(' second', ':').replace(' ','').replace('s', '')
if 'minute' not in correction and 'second' not in correction:
duration = duration + '00:00'
elif 'minute' not in correction and 'second' in correction:
duration = duration.replace(':',':00:')
elif 'second' not in correction:
duration = duration + '00'
secs = sum(int(x) * 60 ** i for i, x in enumerate(reversed(duration.split(':'))))
How do I improve it?
This returns total number of seconds, which seems to be what you wanted:
def parsex(s):
hh = mm = ss = 0
for word in s.split():
word = word.lower()
if word.isdigit():
save = word
elif word.startswith('hour'):
hh = int(save)
elif word.startswith('minute'):
mm = int(save)
elif word.startswith('second'):
ss = int(save)
return (hh*60+mm)*60+ss
print(parsex('1 hour and 30 seconds'))
print(parsex('2 hours 15 minutes 45 seconds'))
You can use datetime library to convert this type of string to proper formatted string.
from datetime import datetime
def format_time(string):
format_string = ''
if 'hour' in string:
if 'hours' in string:
format_string += '%H hours '
else:
format_string += '%H hour '
if 'minute' in string:
if 'minutes' in string:
format_string += '%M minutes '
else:
format_string += '%M minute '
if 'second' in string:
if 'seconds' in string:
format_string += '%S seconds'
else:
format_string += '%S second'
value = datetime.strptime(string, format_string)
return value.strftime('%H:%M:%S')
string = '5 hours 20 minutes 6 seconds'
print(format_time(string))
string = '1 hour 25 seconds'
print(format_time(string))
string = '1 minute 25 seconds'
print(format_time(string))
Output
05:20:06
01:00:25
00:01:25
from collections import defaultdict
dataexp = [
("5 hours 20 minutes 6 seconds","05:20:06"),
("1 hour 25 seconds","01:00:25")
]
def convert(input_):
words = input_.replace('and','').split()
di = defaultdict(lambda:0)
while words:
num = int(words.pop(0))
unit = words.pop(0)[0]
di[unit] = num
return f"{di['h']:02}:{di['m']:02}:{di['s']:02}"
for inp, exp in dataexp:
got = convert(inp)
msg = "\nfor %-100.100s \nexp :%s:\ngot :%s:\n" % (inp, exp, got)
if exp == got:
print("✅! %s" % msg)
else:
print("❌! %s" % msg)
which outputs:
✅!
for 5 hours 20 minutes 6 seconds
exp :05:20:06:
got :05:20:06:
✅!
for 1 hour 25 seconds
exp :01:00:25:
got :01:00:25:
I have this code
today = datetime.now().date()
# prints: 2022/1/14
rd = REL.relativedelta(days=1, weekday=REL.SU)
nextSunday = today + rd
#prints : 2022/1/16
How do i add 10 hours to the date so i can get a variable nextSunday_10am that i can substract to the current time
difference = nextSunday_10am - today
and schedule what I need to do
You can do the same thing as suggested by #Dani3le_ more directly with the following:
def getSundayTime(tme: datetime.date) -> datetime:
nxt_sndy = tme + timedelta(days= 6 - tme.weekday())
return datetime.combine(nxt_sndy, datetime.strptime('10:00', '%H:%M').time())
This will compute calculate the next Sunday and set time to 10:00
You can add hours to a DateTime by using datetime.timedelta().
nextSunday += datetime.timedelta(hours=10)
For example:
import datetime
today = datetime.datetime.today()
print("Today is "+str(today))
while today.weekday()+1 != 6: #0 = "Monday", 1 = "Tuesday"...
today += datetime.timedelta(1)
nextSunday = today + datetime.timedelta(hours=10)
print("Next sunday +10hrs will be "+str(nextSunday))
I use below example for round time in odoo.
#api.one
#api.depends('start','finish','pause')
def total(self):
for rec in self:
time1 = datetime.strptime(rec.start, "%Y-%m-%d %H:%M:%S")
time2 = datetime.strptime(rec.finish, "%Y-%m-%d %H:%M:%S")
rec.total_time = round(((time2 - time1).seconds / float(60*60) - self.pause))
For example:
if start = 07:57:21 , finish = 16:25:36, pause = 1 get result 7 hours
if start = 07:57:34 , finish = 16:28:42, pause = 1 get result 8 hours
First and second time different is 3 minutes but in result that is one hours!
How change round if total time >= 7 hours 30 minutes 01 second I need result 8 in other solution 7.5 (7 hours and 30 minutes)
For "%Y-%m-%d %H:%M:%S" you can use DEFAULT_SERVER_DATETIME_FORMAT
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
For your problem you can use round(x, n). Example:
round(7.4, 0) = 7
round(7.5, 0) = 8
round(7.5, 1) = 7.5
Here you need n = 1 for 7.5 and n=0 for the 'standard' round. You can check 7.5 with ((7.5 - 0.5) % 1) == 0 and convert it from boolean to int directly with int()
The general solution is:
#api.one
#api.depends('start','finish','pause')
def total(self):
for rec in self:
time1 = datetime.strptime(rec.start, DEFAULT_SERVER_DATETIME_FORMAT)
time2 = datetime.strptime(rec.finish, DEFAULT_SERVER_DATETIME_FORMAT)
total_time = (time2 - time1).seconds / float(60*60) - self.pause
rec.total_time = round(total_time, int(((total_time - 0.5) % 1) == 0))
#api.one
#api.depends('start','finish','pause')
def total(self):
for rec in self:
time1 = datetime.strptime(rec.start, DEFAULT_SERVER_DATETIME_FORMAT)
time2 = datetime.strptime(rec.finish, DEFAULT_SERVER_DATETIME_FORMAT)
total_time = (time2 - time1).seconds / float(60*60) - self.pause
total_time = 2*total_time
if 2*total_time%1 <=0.5 :
res = round(total_time)
else :
res = round(2*total_time)
rec.total_time = res
This question already has answers here:
How to get the last day of the month?
(44 answers)
Closed 8 years ago.
This is my first post here so please let me know if I'm doing this wrong...
I'm looking to take the last day of each month for the last 60 months, from a reference date.
For example, if the reference date is today (Aug 21 2014), then the last end of month is July 31st, 2014, and the one before that is June 30th, 2014...
Does anyone know how to do this in python?
Thanks!
Here's an easier/cleaner way that makes use of the datetime module:
>>> import datetime
>>> def prevMonthEnd(startDate):
... ''' given a datetime object, return another datetime object that
... is set to the last day of the prevoius month '''
... firstOfMonth = startDate.replace(day=1)
... return firstOfMonth - datetime.timedelta(days=1)
...
>>> theDate = datetime.date.today()
>>> for i in range(60):
... theDate = prevMonthEnd(theDate)
... print theDate
...
2014-07-31
2014-06-30
2014-05-31
2014-04-30
2014-03-31
2014-02-28
2014-01-31
2013-12-31
(etc.)
Figured it out:
import calendar
m = int(raw_input("m: "))
y = int(raw_input("y: "))
meArr = []
monthsleft = 60
for i in range(1,int(m)):
meArr = meArr + [str(calendar.monthrange(y,i)[1]) + '.' + str(i) + '.' + str(y)]
monthsleft = monthsleft - len(meArr)
while monthsleft > 0:
if monthsleft >= 12:
y = y - 1
for i in range(12,0,-1):
meArr = [str(calendar.monthrange(y,i)[1]) + '.' + str(i) + '.' + str(y)] + meArr
else:
y = y - 1
for i in range(12,m-1,-1):
meArr = [str(calendar.monthrange(y,i)[1]) + '.' + str(i) + '.' + str(y)] + meArr
monthsleft = monthsleft - 12
## print(len(meArr))
I have given date strings like these:
Mon Jun 28 10:51:07 2010
Fri Jun 18 10:18:43 2010
Wed Dec 15 09:18:43 2010
What is a handy python way to calculate the difference in days? Assuming the time zone is the same.
The strings were returned by linux commands.
Edit: Thank you, so many good answers
Use strptime.
Sample usage:
from datetime import datetime
my_date = datetime.strptime('Mon Jun 28 10:51:07 2010', '%a %b %d %H:%M:%S %Y')
print my_date
EDIT:
You could also print the time difference in a human readable form, like so:
from time import strptime
from datetime import datetime
def date_diff(older, newer):
"""
Returns a humanized string representing time difference
The output rounds up to days, hours, minutes, or seconds.
4 days 5 hours returns '4 days'
0 days 4 hours 3 minutes returns '4 hours', etc...
"""
timeDiff = newer - older
days = timeDiff.days
hours = timeDiff.seconds/3600
minutes = timeDiff.seconds%3600/60
seconds = timeDiff.seconds%3600%60
str = ""
tStr = ""
if days > 0:
if days == 1: tStr = "day"
else: tStr = "days"
str = str + "%s %s" %(days, tStr)
return str
elif hours > 0:
if hours == 1: tStr = "hour"
else: tStr = "hours"
str = str + "%s %s" %(hours, tStr)
return str
elif minutes > 0:
if minutes == 1:tStr = "min"
else: tStr = "mins"
str = str + "%s %s" %(minutes, tStr)
return str
elif seconds > 0:
if seconds == 1:tStr = "sec"
else: tStr = "secs"
str = str + "%s %s" %(seconds, tStr)
return str
else:
return None
older = datetime.strptime('Mon Jun 28 10:51:07 2010', '%a %b %d %H:%M:%S %Y')
newer = datetime.strptime('Tue Jun 28 10:52:07 2010', '%a %b %d %H:%M:%S %Y')
print date_diff(older, newer)
Original source for the time snippet.
#!/usr/bin/env python
import datetime
def hrdd(d1, d2):
"""
Human-readable date difference.
"""
_d1 = datetime.datetime.strptime(d1, "%a %b %d %H:%M:%S %Y")
_d2 = datetime.datetime.strptime(d2, "%a %b %d %H:%M:%S %Y")
diff = _d2 - _d1
return diff.days # <-- alternatively: diff.seconds
if __name__ == '__main__':
d1 = "Mon Jun 28 10:51:07 2010"
d2 = "Fri Jun 18 10:18:43 2010"
d3 = "Wed Dec 15 09:18:43 2010"
print hrdd(d1, d2)
# ==> -11
print hrdd(d2, d1)
# ==> 10
print hrdd(d1, d3)
# ==> 169
# ...
>>> import datetime
>>> a = datetime.datetime.strptime("Mon Jun 28 10:51:07 2010", "%a %b %d %H:%M:%S %Y")
>>> b = datetime.datetime.strptime("Fri Jun 18 10:18:43 2010", "%a %b %d %H:%M:%S %Y")
>>> c = a-b
>>> c.days
10
This isn't along the same lines as the other answers, but it might be helpful to someone wanting to display something more human readable (and less precise). I did this quickly, so suggestions welcome.
(Note that it assumes until_seconds is the later timestamp.)
def readable_delta(from_seconds, until_seconds=None):
'''Returns a nice readable delta.
readable_delta(1, 2) # 1 second ago
readable_delta(1000, 2000) # 16 minutes ago
readable_delta(1000, 9000) # 2 hours, 133 minutes ago
readable_delta(1000, 987650) # 11 days ago
readable_delta(1000) # 15049 days ago (relative to now)
'''
if not until_seconds:
until_seconds = time.time()
seconds = until_seconds - from_seconds
delta = datetime.timedelta(seconds=seconds)
# deltas store time as seconds and days, we have to get hours and minutes ourselves
delta_minutes = delta.seconds // 60
delta_hours = delta_minutes // 60
## show a fuzzy but useful approximation of the time delta
if delta.days:
return '%d day%s ago' % (delta.days, plur(delta.days))
elif delta_hours:
return '%d hour%s, %d minute%s ago' % (delta_hours, plur(delta_hours), delta_minutes, plur(delta_minutes))
elif delta_minutes:
return '%d minute%s ago' % (delta_minutes, plur(delta_minutes))
else:
return '%d second%s ago' % (delta.seconds, plur(delta.seconds))
def plur(it):
'''Quick way to know when you should pluralize something.'''
try:
size = len(it)
except TypeError:
size = int(it)
return '' if size==1 else 's'
Here is an improved version of date_diff() routine by #the_void. It will print difference in the following fashion depending on how much the difference is:
1d
12 sec
30 min 12 sec
3h 30m
5d 3h 30m
Here is the routine:
def date_diff(newer, older):
if newer < older:
return '-1'
timeDiff = newer - older
days = int(timeDiff.days)
hours = int(timeDiff.seconds/3600)
minutes = int(timeDiff.seconds%3600/60)
seconds = int(timeDiff.seconds%3600%60)
str = ""
tStr = ""
if days > 0:
tStr = "d"
str = str + "%s%s " %(days, tStr)
if hours > 0:
tStr = "h"
str = str + "%s%s " %(hours, tStr)
if minutes > 0:
if days == 0 and hours == 0:
tStr = 'min'
str = str + "%s %s " %(minutes, tStr)
else:
tStr = "m"
str = str + "%s%s " %(minutes, tStr)
if days == 0 and hours == 0:
if seconds >= 0:
if days == 0 and hours == 0:
tStr = "sec"
str = str + "%s %s" %(seconds, tStr)
else:
tStr = 's'
str = str + "%s%s" %(seconds, tStr)
return str
Try this:
>>> (datetime.datetime.strptime("Mon Jun 28 10:51:07 2010", "%a %b %d %H:%M:%S %Y") - datetime.datetime.strptime("Fri Jun 18 10:18:43 2010", "%a %b %d %H:%M:%S %Y")).days
10
from datetime import datetime
resp = raw_input("What is the first date ?")
date1 = datetime.strptime(resp,"%a %b %d %H:%M:%S %Y")
resp2 = raw_input("What is the second date ?")
date2 = datetime.strptime(resp2,"%a %b %d %H:%M:%S %Y")
res = date2-date1
print str(res)
For details on how to print a timedelta object better, you can see this previous post.