I get a start_date like this:
from django.utils.timezone import utc
import datetime
start_date = datetime.datetime.utcnow().replace(tzinfo=utc)
end_date = datetime.datetime.utcnow().replace(tzinfo=utc)
duration = end_date - start_date
I get output like this:
datetime.timedelta(0, 5, 41038)
How do I convert this into normal time like the following?
10 minutes, 1 hour like this
There's no built-in formatter for timedelta objects, but it's pretty easy to do it yourself:
days, seconds = duration.days, duration.seconds
hours = days * 24 + seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60
Or, equivalently, if you're in Python 2.7+ or 3.2+:
seconds = duration.total_seconds()
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60
Now you can print it however you want:
'{} minutes, {} hours'.format(minutes, hours)
For example:
def convert_timedelta(duration):
days, seconds = duration.days, duration.seconds
hours = days * 24 + seconds // 3600
minutes = (seconds % 3600) // 60
seconds = (seconds % 60)
return hours, minutes, seconds
td = datetime.timedelta(2, 7743, 12345)
hours, minutes, seconds = convert_timedelta(td)
print '{} minutes, {} hours'.format(minutes, hours)
This will print:
9 minutes, 50 hours
If you want to get "10 minutes, 1 hour" instead of "10 minutes, 1 hours", you need to do that manually too:
print '{} minute{}, {} hour{}'.format(minutes, 's' if minutes != 1 else '',
hours, 's' if minutes != 1 else '')
Or you may want to write an english_plural function to do the 's' bits for you, instead of repeating yourself.
From your comments, it sounds like you actually want to keep the days separate. That's even easier:
def convert_timedelta(duration):
days, seconds = duration.days, duration.seconds
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = (seconds % 60)
return days, hours, minutes, seconds
If you want to convert this to a single value to store in a database, then convert that single value back to format it, do this:
def dhms_to_seconds(days, hours, minutes, seconds):
return (((days * 24) + hours) * 60 + minutes) * 60 + seconds
def seconds_to_dhms(seconds):
days = seconds // (3600 * 24)
hours = (seconds // 3600) % 24
minutes = (seconds // 60) % 60
seconds = seconds % 60
return days, hours, minutes, seconds
So, putting it together:
def store_timedelta_in_database(thingy, duration):
seconds = dhms_to_seconds(*convert_timedelta(duration))
db.execute('INSERT INTO foo (thingy, duration) VALUES (?, ?)',
thingy, seconds)
db.commit()
def print_timedelta_from_database(thingy):
cur = db.execute('SELECT duration FROM foo WHERE thingy = ?', thingy)
seconds = int(cur.fetchone()[0])
days, hours, minutes, seconds = seconds_to_dhms(seconds)
print '{} took {} minutes, {} hours, {} days'.format(thingy, minutes, hours, days)
A datetime.timedelta corresponds to the difference between two dates, not a date itself. It's only expressed in terms of days, seconds, and microseconds, since larger time units like months and years don't decompose cleanly (is 30 days 1 month or 0.9677 months?).
If you want to convert a timedelta into hours and minutes, you can use the total_seconds() method to get the total number of seconds and then do some math:
x = datetime.timedelta(1, 5, 41038) # Interval of 1 day and 5.41038 seconds
secs = x.total_seconds()
hours = int(secs / 3600)
minutes = int(secs / 60) % 60
There is no need for custom helper functions if all we need is to print the string of the form [D day[s], ][H]H:MM:SS[.UUUUUU]. timedelta object supports str() operation that will do this. It works even in Python 2.6.
>>> from datetime import timedelta
>>> timedelta(seconds=90136)
datetime.timedelta(1, 3736)
>>> str(timedelta(seconds=90136))
'1 day, 1:02:16'
I don't think it's a good idea to caculate yourself.
If you just want a pretty output, just covert it into str with str() function or directly print() it.
And if there's further usage of the hours and minutes, you can parse it to datetime object use datetime.strptime()(and extract the time part with datetime.time() mehtod), for example:
import datetime
delta = datetime.timedelta(seconds=10000)
time_obj = datetime.datetime.strptime(str(delta),'%H:%M:%S').time()
Just use strftime :)
Something like that:
my_date = datetime.datetime(2013, 1, 7, 10, 31, 34, 243366, tzinfo=<UTC>)
print(my_date.strftime("%Y, %d %B"))
After edited your question to format timedelta, you could use:
def timedelta_tuple(timedelta_object):
return timedelta_object.days, timedelta_object.seconds//3600, (timedelta_object.seconds//60)%60
# Try this code
from datetime import timedelta
class TimeDelta(timedelta):
def __str__(self):
_times = super(TimeDelta, self).__str__().split(':')
if "," in _times[0]:
_hour = int(_times[0].split(',')[-1].strip())
if _hour:
_times[0] += " hours" if _hour > 1 else " hour"
else:
_times[0] = _times[0].split(',')[0]
else:
_hour = int(_times[0].strip())
if _hour:
_times[0] += " hours" if _hour > 1 else " hour"
else:
_times[0] = ""
_min = int(_times[1])
if _min:
_times[1] += " minutes" if _min > 1 else " minute"
else:
_times[1] = ""
_sec = int(_times[2])
if _sec:
_times[2] += " seconds" if _sec > 1 else " second"
else:
_times[2] = ""
return ", ".join([i for i in _times if i]).strip(" ,").title()
# Test
>>> str(TimeDelta(seconds=10))
'10 Seconds'
>>> str(TimeDelta(seconds=60))
'01 Minute'
>>> str(TimeDelta(seconds=90))
'01 Minute, 30 Seconds'
>>> str(TimeDelta(seconds=3000))
'50 Minutes'
>>> str(TimeDelta(seconds=3600))
'1 Hour'
>>> str(TimeDelta(seconds=3690))
'1 Hour, 01 Minute, 30 Seconds'
>>> str(TimeDelta(seconds=3660))
'1 Hour, 01 Minute'
>>> str(TimeDelta(seconds=3630))
'1 Hour, 30 Seconds'
>>> str(TimeDelta(seconds=3600*20))
'20 Hours'
>>> str(TimeDelta(seconds=3600*20 + 3000))
'20 Hours, 50 Minutes'
>>> str(TimeDelta(seconds=3600*20 + 3630))
'21 Hours, 30 Seconds'
>>> str(TimeDelta(seconds=3600*20 + 3660))
'21 Hours, 01 Minute'
>>> str(TimeDelta(seconds=3600*20 + 3690))
'21 Hours, 01 Minute, 30 Seconds'
>>> str(TimeDelta(seconds=3600*24))
'1 Day'
>>> str(TimeDelta(seconds=3600*24 + 10))
'1 Day, 10 Seconds'
>>> str(TimeDelta(seconds=3600*24 + 60))
'1 Day, 01 Minute'
>>> str(TimeDelta(seconds=3600*24 + 90))
'1 Day, 01 Minute, 30 Seconds'
>>> str(TimeDelta(seconds=3600*24 + 3000))
'1 Day, 50 Minutes'
>>> str(TimeDelta(seconds=3600*24 + 3600))
'1 Day, 1 Hour'
>>> str(TimeDelta(seconds=3600*24 + 3630))
'1 Day, 1 Hour, 30 Seconds'
>>> str(TimeDelta(seconds=3600*24 + 3660))
'1 Day, 1 Hour, 01 Minute'
>>> str(TimeDelta(seconds=3600*24 + 3690))
'1 Day, 1 Hour, 01 Minute, 30 Seconds'
>>> str(TimeDelta(seconds=3600*24*2))
'2 Days'
>>> str(TimeDelta(seconds=3600*24*2 + 9999))
'2 Days, 2 Hours, 46 Minutes, 39 Seconds'
I defined own helper function to convert timedelta object to 'HH:MM:SS' format - only hours, minutes and seconds, without changing hours to days.
def format_timedelta(td):
hours, remainder = divmod(td.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)
hours, minutes, seconds = int(hours), int(minutes), int(seconds)
if hours < 10:
hours = '0%s' % int(hours)
if minutes < 10:
minutes = '0%s' % minutes
if seconds < 10:
seconds = '0%s' % seconds
return '%s:%s:%s' % (hours, minutes, seconds)
An alternative for this (older) question is to create a relative time from a timedelta converted to seconds. This can be accomplished using the time.gmtime(...) method that accepts seconds since the epoch:
>>> time.strftime("%H:%M:%S",time.gmtime(36901)) # secs = 36901
'10:15:01'
And, that's it! (NOTE: Here's a link to format specifiers for time.strftime() so the difference can be truncated to any units, as needed. ...)
Notably, this technique is also a great way to tell if your current time zone is actually in daylight savings time or not. (It provides an offset of 0 or 1 hours meaning it can be interpreted basically as a boolean.)
import datetime
import pytz
import time
pacific=pytz.timezone('US/Pacific')
now=datetime.datetime.now()
# pacific.dst(now).total_seconds() yields 3600 secs. [aka 1 hour]
time.strftime("%-H", time.gmtime(pacific.dst(now).total_seconds()))
'1'
This can be rendered to a method is_standard_time(...) where 1 means true and 0 means false.
Do you want to print the date in that format? This is the Python documentation: http://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
>>> a = datetime.datetime(2013, 1, 7, 10, 31, 34, 243366)
>>> print a.strftime('%Y %d %B, %M:%S%p')
>>> 2013 07 January, 31:34AM
For the timedelta:
>>> a = datetime.timedelta(0,5,41038)
>>> print '%s seconds, %s microseconds' % (a.seconds, a.microseconds)
But please notice, you should make sure it has the related value. For the above cases, it doesn't have the hours and minute values, and you should calculate from the seconds.
datetime.timedelta(hours=1, minutes=10)
#python 2.7
I want some how to print a message like:
"Since then, x days, y hours, z minutes and w seconds have elapsed".
Currently I'm doing something like this but I miss the remainders plus (most importantly) I don't like it. There should be something more beautiful
dt = (datetime.now() - datetime(year=1980, month=1, day=1, hour=18)).total_seconds()
full_days = int(dt // (3600 * 24))
full_hours = int((dt - full_days * (24 * 3600)) // 3600)
full_minutes = int((dt - full_days * (24 * 3600) - full_hours * 3600) // 60)
residual_seconds = dt - full_days * (24 * 3600) - full_hours * 3600 - full_minutes * 60
print(full_days, full_hours, full_minutes, residual_seconds)
You can use timedelta:
from datetime import datetime
fmt = 'Since then, {0} days, {1} hours, {2} minutes and {3} seconds have elapsed'
td = datetime.now() - datetime(year=1980, month=1, day=1, hour=18)
print(fmt.format(td.days, td.seconds // 3600, td.seconds % 3600 // 60, td.seconds % 60))
Output:
Since then, 13266 days, 23 hours, 5 minutes and 55 seconds have elapsed
Try this, I hope this will be useful for you:
import datetime
from dateutil.relativedelta import relativedelta
end = '2016-01-01 12:00:00'
begin = '2015-03-01 01:00:00'
start = datetime.datetime.strptime(end, '%Y-%m-%d %H:%M:%S')
ends = datetime.datetime.strptime(begin, '%Y-%m-%d %H:%M:%S')
diff = relativedelta(start, ends)
print "%d year %d month %d days %d hours %d minutes" % (diff.years, diff.months, diff.days, diff.hours, diff.minutes)
Output:
0 year 10 month 0 days 11 hours 0 minutes
There is Humanize to convert all sorts of data into human readable formats.
>>> import humanize
>>> from datetime import datetime, timedelta
>>> humanize.naturaltime(datetime.now() - timedelta(seconds=3600))
'an hour ago'
This may be deemed more beautiful, but I'm not sure it's actually pythonic. Personally I'd just hide away the "ugly" code in a function. Anyway,
dt=datetime(2016,1,2,11,30,50)-datetime(2016,1,1)
s=dt.total_seconds()
t=[]
for x in (24*3600,3600,60,1):
t.append(s//x)
s -= t[-1]*x
days,hours,mins,secs=t
>>> print(t)
[1.0, 11.0, 30.0, 50.0]
How do I tell the time difference in minutes between two datetime objects?
>>> import datetime
>>> first_time = datetime.datetime.now()
>>> later_time = datetime.datetime.now()
>>> difference = later_time - first_time
datetime.timedelta(0, 8, 562000)
>>> seconds_in_day = 24 * 60 * 60
>>> divmod(difference.days * seconds_in_day + difference.seconds, 60)
(0, 8) # 0 minutes, 8 seconds
Subtracting the later time from the first time difference = later_time - first_time creates a datetime object that only holds the difference.
In the example above it is 0 minutes, 8 seconds and 562000 microseconds.
Using datetime example
>>> from datetime import datetime
>>> then = datetime(2012, 3, 5, 23, 8, 15) # Random date in the past
>>> now = datetime.now() # Now
>>> duration = now - then # For build-in functions
>>> duration_in_s = duration.total_seconds() # Total number of seconds between dates
Duration in years
>>> years = divmod(duration_in_s, 31536000)[0] # Seconds in a year=365*24*60*60 = 31536000.
Duration in days
>>> days = duration.days # Build-in datetime function
>>> days = divmod(duration_in_s, 86400)[0] # Seconds in a day = 86400
Duration in hours
>>> hours = divmod(duration_in_s, 3600)[0] # Seconds in an hour = 3600
Duration in minutes
>>> minutes = divmod(duration_in_s, 60)[0] # Seconds in a minute = 60
Duration in seconds
[!] See warning about using duration in seconds in the bottom of this post
>>> seconds = duration.seconds # Build-in datetime function
>>> seconds = duration_in_s
Duration in microseconds
[!] See warning about using duration in microseconds in the bottom of this post
>>> microseconds = duration.microseconds # Build-in datetime function
Total duration between the two dates
>>> days = divmod(duration_in_s, 86400) # Get days (without [0]!)
>>> hours = divmod(days[1], 3600) # Use remainder of days to calc hours
>>> minutes = divmod(hours[1], 60) # Use remainder of hours to calc minutes
>>> seconds = divmod(minutes[1], 1) # Use remainder of minutes to calc seconds
>>> print("Time between dates: %d days, %d hours, %d minutes and %d seconds" % (days[0], hours[0], minutes[0], seconds[0]))
or simply:
>>> print(now - then)
Edit 2019
Since this answer has gained traction, I'll add a function, which might simplify the usage for some
from datetime import datetime
def getDuration(then, now = datetime.now(), interval = "default"):
# Returns a duration as specified by variable interval
# Functions, except totalDuration, returns [quotient, remainder]
duration = now - then # For build-in functions
duration_in_s = duration.total_seconds()
def years():
return divmod(duration_in_s, 31536000) # Seconds in a year=31536000.
def days(seconds = None):
return divmod(seconds if seconds != None else duration_in_s, 86400) # Seconds in a day = 86400
def hours(seconds = None):
return divmod(seconds if seconds != None else duration_in_s, 3600) # Seconds in an hour = 3600
def minutes(seconds = None):
return divmod(seconds if seconds != None else duration_in_s, 60) # Seconds in a minute = 60
def seconds(seconds = None):
if seconds != None:
return divmod(seconds, 1)
return duration_in_s
def totalDuration():
y = years()
d = days(y[1]) # Use remainder to calculate next variable
h = hours(d[1])
m = minutes(h[1])
s = seconds(m[1])
return "Time between dates: {} years, {} days, {} hours, {} minutes and {} seconds".format(int(y[0]), int(d[0]), int(h[0]), int(m[0]), int(s[0]))
return {
'years': int(years()[0]),
'days': int(days()[0]),
'hours': int(hours()[0]),
'minutes': int(minutes()[0]),
'seconds': int(seconds()),
'default': totalDuration()
}[interval]
# Example usage
then = datetime(2012, 3, 5, 23, 8, 15)
now = datetime.now()
print(getDuration(then)) # E.g. Time between dates: 7 years, 208 days, 21 hours, 19 minutes and 15 seconds
print(getDuration(then, now, 'years')) # Prints duration in years
print(getDuration(then, now, 'days')) # days
print(getDuration(then, now, 'hours')) # hours
print(getDuration(then, now, 'minutes')) # minutes
print(getDuration(then, now, 'seconds')) # seconds
Warning: Caveat about built-in .seconds and .microseconds
datetime.seconds and datetime.microseconds are capped to [0,86400) and [0,10^6) respectively.
They should be used carefully if timedelta is bigger than the max returned value.
Examples:
end is 1h and 200μs after start:
>>> start = datetime(2020,12,31,22,0,0,500)
>>> end = datetime(2020,12,31,23,0,0,700)
>>> delta = end - start
>>> delta.microseconds
RESULT: 200
EXPECTED: 3600000200
end is 1d and 1h after start:
>>> start = datetime(2020,12,30,22,0,0)
>>> end = datetime(2020,12,31,23,0,0)
>>> delta = end - start
>>> delta.seconds
RESULT: 3600
EXPECTED: 90000
New at Python 2.7 is the timedelta instance method .total_seconds(). From the Python docs, this is equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6.
Reference: http://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds
>>> import datetime
>>> time1 = datetime.datetime.now()
>>> time2 = datetime.datetime.now() # waited a few minutes before pressing enter
>>> elapsedTime = time2 - time1
>>> elapsedTime
datetime.timedelta(0, 125, 749430)
>>> divmod(elapsedTime.total_seconds(), 60)
(2.0, 5.749430000000004) # divmod returns quotient and remainder
# 2 minutes, 5.74943 seconds
Just subtract one from the other. You get a timedelta object with the difference.
>>> import datetime
>>> d1 = datetime.datetime.now()
>>> d2 = datetime.datetime.now() # after a 5-second or so pause
>>> d2 - d1
datetime.timedelta(0, 5, 203000)
>>> dd = d2 - d1
>>> print (dd.days) # get days
>>> print (dd.seconds) # get seconds
>>> print (dd.microseconds) # get microseconds
>>> print (int(round(dd.total_seconds()/60, 0))) # get minutes
If a, b are datetime objects then to find the time difference between them in Python 3:
from datetime import timedelta
time_difference = a - b
time_difference_in_minutes = time_difference / timedelta(minutes=1)
On earlier Python versions:
time_difference_in_minutes = time_difference.total_seconds() / 60
If a, b are naive datetime objects such as returned by datetime.now() then the result may be wrong if the objects represent local time with different UTC offsets e.g., around DST transitions or for past/future dates. More details: Find if 24 hrs have passed between datetimes - Python.
To get reliable results, use UTC time or timezone-aware datetime objects.
Use divmod:
now = int(time.time()) # epoch seconds
then = now - 90000 # some time in the past
d = divmod(now-then,86400) # days
h = divmod(d[1],3600) # hours
m = divmod(h[1],60) # minutes
s = m[1] # seconds
print '%d days, %d hours, %d minutes, %d seconds' % (d[0],h[0],m[0],s)
To just find the number of days: timedelta has a 'days' attribute. You can simply query that.
>>>from datetime import datetime, timedelta
>>>d1 = datetime(2015, 9, 12, 13, 9, 45)
>>>d2 = datetime(2015, 8, 29, 21, 10, 12)
>>>d3 = d1- d2
>>>print d3
13 days, 15:59:33
>>>print d3.days
13
Just thought it might be useful to mention formatting as well in regards to timedelta. strptime() parses a string representing a time according to a format.
from datetime import datetime
datetimeFormat = '%Y/%m/%d %H:%M:%S.%f'
time1 = '2016/03/16 10:01:28.585'
time2 = '2016/03/16 09:56:28.067'
time_dif = datetime.strptime(time1, datetimeFormat) - datetime.strptime(time2,datetimeFormat)
print(time_dif)
This will output:
0:05:00.518000
This is how I get the number of hours that elapsed between two datetime.datetime objects:
before = datetime.datetime.now()
after = datetime.datetime.now()
hours = math.floor(((after - before).seconds) / 3600)
To get the hour, minute and second, you can do this
>>> import datetime
>>> first_time = datetime.datetime.now()
>>> later_time = datetime.datetime.now()
>>> difference = later_time - first_time
>>> m, s = divmod(difference.total_seconds(), 60)
>>> print("H:M:S is {}:{}:{}".format(m//60, m%60, s))
I use somethign like this :
from datetime import datetime
def check_time_difference(t1: datetime, t2: datetime):
t1_date = datetime(
t1.year,
t1.month,
t1.day,
t1.hour,
t1.minute,
t1.second)
t2_date = datetime(
t2.year,
t2.month,
t2.day,
t2.hour,
t2.minute,
t2.second)
t_elapsed = t1_date - t2_date
return t_elapsed
# usage
f = "%Y-%m-%d %H:%M:%S+01:00"
t1 = datetime.strptime("2018-03-07 22:56:57+01:00", f)
t2 = datetime.strptime("2018-03-07 22:48:05+01:00", f)
elapsed_time = check_time_difference(t1, t2)
print(elapsed_time)
#return : 0:08:52
This will give the difference in seconds (then just divide by 60 to get minutes):
import time
import datetime
t_start = datetime.datetime.now()
time.sleep(10)
t_end = datetime.datetime.now()
elapsedTime = (t_end - t_start )
print(elapsedTime.total_seconds())
outputs:
10.009222
This is the simplest way in my opinion, and you don't need to worry about precision or overflow.
For instance, using elapsedTime.seconds you lose a lot of precision (it returns an integer). Also, elapsedTime.microseconds is capped at 10^6, as this answer pointed out. So, for example, for a 10 second sleep(), elapsedTime.microseconds gives 8325 (which is wrong, should be around 10,000,000).
this is to find the difference between current time and 9.30 am
t=datetime.now()-datetime.now().replace(hour=9,minute=30)
Based on #Attaque great answer, I propose a shorter simplified version of the datetime difference calculator:
seconds_mapping = {
'y': 31536000,
'm': 2628002.88, # this is approximate, 365 / 12; use with caution
'w': 604800,
'd': 86400,
'h': 3600,
'min': 60,
's': 1,
'mil': 0.001,
}
def get_duration(d1, d2, interval, with_reminder=False):
if with_reminder:
return divmod((d2 - d1).total_seconds(), seconds_mapping[interval])
else:
return (d2 - d1).total_seconds() / seconds_mapping[interval]
I've changed it to avoid declaring repetetive functions, removed the pretty print default interval and added support for milliseconds, weeks and ISO months (bare in mind months are just approximate, based on assumption that each month is equal to 365/12).
Which produces:
d1 = datetime(2011, 3, 1, 1, 1, 1, 1000)
d2 = datetime(2011, 4, 1, 1, 1, 1, 2500)
print(get_duration(d1, d2, 'y', True)) # => (0.0, 2678400.0015)
print(get_duration(d1, d2, 'm', True)) # => (1.0, 50397.12149999989)
print(get_duration(d1, d2, 'w', True)) # => (4.0, 259200.00149999978)
print(get_duration(d1, d2, 'd', True)) # => (31.0, 0.0014999997802078724)
print(get_duration(d1, d2, 'h', True)) # => (744.0, 0.0014999997802078724)
print(get_duration(d1, d2, 'min', True)) # => (44640.0, 0.0014999997802078724)
print(get_duration(d1, d2, 's', True)) # => (2678400.0, 0.0014999997802078724)
print(get_duration(d1, d2, 'mil', True)) # => (2678400001.0, 0.0004999997244524721)
print(get_duration(d1, d2, 'y', False)) # => 0.08493150689687975
print(get_duration(d1, d2, 'm', False)) # => 1.019176965856293
print(get_duration(d1, d2, 'w', False)) # => 4.428571431051587
print(get_duration(d1, d2, 'd', False)) # => 31.00000001736111
print(get_duration(d1, d2, 'h', False)) # => 744.0000004166666
print(get_duration(d1, d2, 'min', False)) # => 44640.000024999994
print(get_duration(d1, d2, 's', False)) # => 2678400.0015
print(get_duration(d1, d2, 'mil', False)) # => 2678400001.4999995
This is my approach using mktime.
from datetime import datetime, timedelta
from time import mktime
yesterday = datetime.now() - timedelta(days=1)
today = datetime.now()
difference_in_seconds = abs(mktime(yesterday.timetuple()) - mktime(today.timetuple()))
difference_in_minutes = difference_in_seconds / 60
In Other ways to get difference between date;
import dateutil.parser
import datetime
last_sent_date = "" # date string
timeDifference = current_date - dateutil.parser.parse(last_sent_date)
time_difference_in_minutes = (int(timeDifference.days) * 24 * 60) + int((timeDifference.seconds) / 60)
So get output in Min.
Thanks
I have used time differences for continuous integration tests to check and improve my functions. Here is simple code if somebody need it
from datetime import datetime
class TimeLogger:
time_cursor = None
def pin_time(self):
global time_cursor
time_cursor = datetime.now()
def log(self, text=None) -> float:
global time_cursor
if not time_cursor:
time_cursor = datetime.now()
now = datetime.now()
t_delta = now - time_cursor
seconds = t_delta.total_seconds()
result = str(now) + ' tl -----------> %.5f' % seconds
if text:
result += " " + text
print(result)
self.pin_time()
return seconds
time_logger = TimeLogger()
Using:
from .tests_time_logger import time_logger
class Tests(TestCase):
def test_workflow(self):
time_logger.pin_time()
... my functions here ...
time_logger.log()
... other function(s) ...
time_logger.log(text='Tests finished')
and i have something like that in log output
2019-12-20 17:19:23.635297 tl -----------> 0.00007
2019-12-20 17:19:28.147656 tl -----------> 4.51234 Tests finished
You may find this fast snippet useful in not so much long time intervals:
from datetime import datetime as dttm
time_ago = dttm(2017, 3, 1, 1, 1, 1, 1348)
delta = dttm.now() - time_ago
days = delta.days # can be converted into years which complicates a bit…
hours, minutes, seconds = map(int, delta.__format__('').split('.')[0].split(' ')[-1].split(':'))
tested on Python v.3.8.6
Here is an answer that is easy to generalise or turn into a function and which is reasonable compact and easy to follow.
ts_start=datetime(2020, 12, 1, 3, 9, 45)
ts_end=datetime.now()
ts_diff=ts_end-ts_start
secs=ts_diff.total_seconds()
days,secs=divmod(secs,secs_per_day:=60*60*24)
hrs,secs=divmod(secs,secs_per_hr:=60*60)
mins,secs=divmod(secs,secs_per_min:=60)
secs=round(secs, 2)
answer='Duration={} days, {} hrs, {} mins and {} secs'.format(int(days),int(hrs),int(mins),secs)
print(answer)
It gives an answer in the form Duration=270 days, 10 hrs, 32 mins and 42.13 secs
This might help someone, find is expired or not with this method its calculating with days. There are dt.seconds and dt.microseconds also available
from datetime import datetime
# updated_at = "2022-10-20T07:18:56.950563"
def is_expired(updated_at):
expires_in = 7 #days
datetime_format = '%Y-%m-%dT%H:%M:%S.%f'
time_difference = datetime.now() - datetime.strptime(updated_at, datetime_format)
return True if time_difference.days > expires_in else False
import datetime
date = datetime.date(1, 1, 1)
#combine a dummy date to the time
datetime1 = datetime.datetime.combine(date, start_time)
datetime2 = datetime.datetime.combine(date, stop_time)
#compute the difference
time_elapsed = datetime1 - datetime2
start_time --> start time for datetime object
end_time--> end time for datetime object
we cannot directly subtract the datetime.time objects
hence we need to add a random date to it (we use combine)
or you can use the "today" instead of (1,1,1)
hope this helps