Can't calculate the difference between 2 days in hours [duplicate] - python

This question already has answers here:
How do I check the difference, in seconds, between two dates?
(7 answers)
Closed 8 years ago.
I need to check if some date and now arent' different more than in 18 hours:
dt = parser.parse("some date 123") #working well
diff = datetime.datetime.now() - dt
print "datetime.datetime.now() - dt = %s" % diff # 31 days, 0:08:04.882498 -- correct
print "datetime.datetime.now() - dt seconds = %s" % diff.seconds # 484 -- too
(datetime.datetime.now() - dt).seconds / 3600) < 18 # returns True always
As you can see, even though the dates are different in 31 days, the amount of seconds if very little which doesn't allow me to calculate the amount of hours. Why is it so small? Should it be x * 60 * 60 * amount_of_days? And how can I do what I want?

seconds is returning just the number of seconds, not the total number of seconds, for that you can use timedelta.total_seconds.

You may try this:
from datetime import date
date0 = date(2014, 9, 07)
date1 = date(2014, 9, 05)
diff = date0 - date1
print diff.days * 24
Also check How do I check the difference, in seconds, between two dates?
or
>>> from datetime import datetime
>>> date0 = datetime(2014,09,07,0,0,0)
>>> date1 = datetime(2014,09,01,23,59,59)
>>> date0-date1
datetime.timedelta(6, 1)
>>> (date0-date1).days * 24
144

Related

Converting seconds to minutes and hours and writing to a CSV file [duplicate]

I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds.
Is there an easy way to convert the seconds to this format in Python?
You can use datetime.timedelta function:
>>> import datetime
>>> str(datetime.timedelta(seconds=666))
'0:11:06'
By using the divmod() function, which does only a single division to produce both the quotient and the remainder, you can have the result very quickly with only two mathematical operations:
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
And then use string formatting to convert the result into your desired output:
print('{:d}:{:02d}:{:02d}'.format(h, m, s)) # Python 3
print(f'{h:d}:{m:02d}:{s:02d}') # Python 3.6+
I can hardly name that an easy way (at least I can't remember the syntax), but it is possible to use time.strftime, which gives more control over formatting:
from time import strftime
from time import gmtime
strftime("%H:%M:%S", gmtime(666))
'00:11:06'
strftime("%H:%M:%S", gmtime(60*60*24))
'00:00:00'
gmtime is used to convert seconds to special tuple format that strftime() requires.
Note: Truncates after 23:59:59
Using datetime:
With the ':0>8' format:
from datetime import timedelta
"{:0>8}".format(str(timedelta(seconds=66)))
# Result: '00:01:06'
"{:0>8}".format(str(timedelta(seconds=666777)))
# Result: '7 days, 17:12:57'
"{:0>8}".format(str(timedelta(seconds=60*60*49+109)))
# Result: '2 days, 1:01:49'
Without the ':0>8' format:
"{}".format(str(timedelta(seconds=66)))
# Result: '00:01:06'
"{}".format(str(timedelta(seconds=666777)))
# Result: '7 days, 17:12:57'
"{}".format(str(timedelta(seconds=60*60*49+109)))
# Result: '2 days, 1:01:49'
Using time:
from time import gmtime
from time import strftime
# NOTE: The following resets if it goes over 23:59:59!
strftime("%H:%M:%S", gmtime(125))
# Result: '00:02:05'
strftime("%H:%M:%S", gmtime(60*60*24-1))
# Result: '23:59:59'
strftime("%H:%M:%S", gmtime(60*60*24))
# Result: '00:00:00'
strftime("%H:%M:%S", gmtime(666777))
# Result: '17:12:57'
# Wrong
This is my quick trick:
from humanfriendly import format_timespan
secondsPassed = 1302
format_timespan(secondsPassed)
# '21 minutes and 42 seconds'
For more info Visit:
https://humanfriendly.readthedocs.io/en/latest/api.html#humanfriendly.format_timespan
The following set worked for me.
def sec_to_hours(seconds):
a=str(seconds//3600)
b=str((seconds%3600)//60)
c=str((seconds%3600)%60)
d=["{} hours {} mins {} seconds".format(a, b, c)]
return d
print(sec_to_hours(10000))
# ['2 hours 46 mins 40 seconds']
print(sec_to_hours(60*60*24+105))
# ['24 hours 1 mins 45 seconds']
A bit off topic answer but maybe useful to someone
def time_format(seconds: int) -> str:
if seconds is not None:
seconds = int(seconds)
d = seconds // (3600 * 24)
h = seconds // 3600 % 24
m = seconds % 3600 // 60
s = seconds % 3600 % 60
if d > 0:
return '{:02d}D {:02d}H {:02d}m {:02d}s'.format(d, h, m, s)
elif h > 0:
return '{:02d}H {:02d}m {:02d}s'.format(h, m, s)
elif m > 0:
return '{:02d}m {:02d}s'.format(m, s)
elif s > 0:
return '{:02d}s'.format(s)
return '-'
Results in:
print(time_format(25*60*60 + 125))
>>> 01D 01H 02m 05s
print(time_format(17*60*60 + 35))
>>> 17H 00m 35s
print(time_format(3500))
>>> 58m 20s
print(time_format(21))
>>> 21s
This is how I got it.
def sec2time(sec, n_msec=3):
''' Convert seconds to 'D days, HH:MM:SS.FFF' '''
if hasattr(sec,'__len__'):
return [sec2time(s) for s in sec]
m, s = divmod(sec, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
if n_msec > 0:
pattern = '%%02d:%%02d:%%0%d.%df' % (n_msec+3, n_msec)
else:
pattern = r'%02d:%02d:%02d'
if d == 0:
return pattern % (h, m, s)
return ('%d days, ' + pattern) % (d, h, m, s)
Some examples:
$ sec2time(10, 3)
Out: '00:00:10.000'
$ sec2time(1234567.8910, 0)
Out: '14 days, 06:56:07'
$ sec2time(1234567.8910, 4)
Out: '14 days, 06:56:07.8910'
$ sec2time([12, 345678.9], 3)
Out: ['00:00:12.000', '4 days, 00:01:18.900']
hours (h) calculated by floor division (by //) of seconds by 3600 (60 min/hr * 60 sec/min)
minutes (m) calculated by floor division of remaining seconds (remainder from hour calculation, by %) by 60 (60 sec/min)
similarly, seconds (s) by remainder of hour and minutes calculation.
Rest is just string formatting!
def hms(seconds):
h = seconds // 3600
m = seconds % 3600 // 60
s = seconds % 3600 % 60
return '{:02d}:{:02d}:{:02d}'.format(h, m, s)
print(hms(7500)) # Should print 02h05m00s
If you need to get datetime.time value, you can use this trick:
my_time = (datetime(1970,1,1) + timedelta(seconds=my_seconds)).time()
You cannot add timedelta to time, but can add it to datetime.
UPD: Yet another variation of the same technique:
my_time = (datetime.fromordinal(1) + timedelta(seconds=my_seconds)).time()
Instead of 1 you can use any number greater than 0. Here we use the fact that datetime.fromordinal will always return datetime object with time component being zero.
dateutil.relativedelta is convenient if you need to access hours, minutes and seconds as floats as well. datetime.timedelta does not provide a similar interface.
from dateutil.relativedelta import relativedelta
rt = relativedelta(seconds=5440)
print(rt.seconds)
print('{:02d}:{:02d}:{:02d}'.format(
int(rt.hours), int(rt.minutes), int(rt.seconds)))
Prints
40.0
01:30:40
Here is a way that I always use: (no matter how inefficient it is)
seconds = 19346
def zeroes (num):
if num < 10: num = "0" + num
return num
def return_hms(second, apply_zeroes):
sec = second % 60
min_ = second // 60 % 60
hrs = second // 3600
if apply_zeroes > 0:
sec = zeroes(sec)
min_ = zeroes(min_)
if apply_zeroes > 1:
hrs = zeroes(hrs)
return "{}:{}:{}".format(hrs, min_, sec)
print(return_hms(seconds, 1))
RESULT:
5:22:26
Syntax of return_hms() function
The return_hms() function is used like this:
The first variable (second) is the amount of seconds you want to convert into h:m:s.
The second variable (apply_zeroes) is formatting:
0 or less: Apply no zeroes whatsoever
1: Apply zeroes to minutes and seconds when they're below 10.
2 or more: Apply zeroes to any value (including hours) when they're below 10.
Here is a simple program that reads the current time and converts it to a time of day in hours, minutes, and seconds
import time as tm #import package time
timenow = tm.ctime() #fetch local time in string format
timeinhrs = timenow[11:19]
t=tm.time()#time.time() gives out time in seconds since epoch.
print("Time in HH:MM:SS format is: ",timeinhrs,"\nTime since epoch is : ",t/(3600*24),"days")
The output is
Time in HH:MM:SS format is: 13:32:45
Time since epoch is : 18793.335252338384 days
You can divide seconds by 60 to get the minutes
import time
seconds = time.time()
minutes = seconds / 60
print(minutes)
When you divide it by 60 again, you will get the hours
In my case I wanted to achieve format
"HH:MM:SS.fff".
I solved it like this:
timestamp = 28.97000002861023
str(datetime.fromtimestamp(timestamp)+timedelta(hours=-1)).split(' ')[1][:12]
'00:00:28.970'
The solutions above will work if you're looking to convert a single value for "seconds since midnight" on a date to a datetime object or a string with HH:MM:SS, but I landed on this page because I wanted to do this on a whole dataframe column in pandas. If anyone else is wondering how to do this for more than a single value at a time, what ended up working for me was:
mydate='2015-03-01'
df['datetime'] = datetime.datetime(mydate) + \
pandas.to_timedelta(df['seconds_since_midnight'], 's')
I looked every answers here and still tried my own
def a(t):
print(f"{int(t/3600)}H {int((t/60)%60) if t/3600>0 else int(t/60)}M {int(t%60)}S")
Results:
>>> a(7500)
2H 5M 0S
>>> a(3666)
1H 1M 6S
Python: 3.8.8
division = 3623 // 3600 #to hours
division2 = 600 // 60 #to minutes
print (division) #write hours
print (division2) #write minutes
PS My code is unprofessional

Python timedelta in full days, full hours and so on

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]

Python - time difference in milliseconds not working for me

I've read a few posts about this and thought I had some code that worked. If the difference between the 2 values is less than a 1sec then the millisecs displayed is correct.
If the difference is more than a sec, its still only showing me the difference of the millisecs.
As below.
Correct:
now_wind 2013-08-25 08:43:04.776209
first_time_wind 2013-08-25 08:43:04.506301
time_diff 0:00:00.269908
diff 269
Wrong - this should be 2000 + 76?:
now_wind 2013-08-25 08:43:25.660427
first_time_wind 2013-08-25 08:43:23.583902
time_diff 0:00:02.076525
diff 76
#!/usr/bin/env python
import datetime
import time
from time import sleep
first_time_wind = datetime.datetime.now()
sleep (2)
now_wind = datetime.datetime.now()
print "now_wind", now_wind
print "first_time_wind", first_time_wind
time_diff_wind = (now_wind - first_time_wind)
print "time_diff", time_diff_wind
print "diff", time_diff_wind.microseconds / 1000
Try using total_seconds method:
print time_diff_wind.total_seconds() * 1000
That method is equivalent to: (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
Note: It's available since version 2.7
>>> a = datetime.datetime.now()
>>> b = datetime.datetime.now()
>>> a
datetime.datetime(2013, 8, 25, 2, 5, 1, 879000)
>>> b
datetime.datetime(2013, 8, 25, 2, 5, 8, 984000)
>>> a - b
datetime.timedelta(-1, 86392, 895000)
>>> b - a
datetime.timedelta(0, 7, 105000)
>>> (b - a).microseconds
105000
>>> (b - a).seconds
7
>>> (b - a).microseconds / 1000
105
your microseconds don't include the seconds that have passed
The correct answer (in 2020) is:
>>> from datetime import timedelta
>>> timedelta(days=1, milliseconds=50) / timedelta(milliseconds=1)
86400050.0
The other answers lose precision and/or are more verbose.
I faced this issue as well, but in my case I need real milliseconds precision, so using total_seconds() * 1000 isn't an option for me, so what I did is:
def millis_interval(start, end):
"""start and end are datetime instances"""
diff = end - start
millis = diff.days * 24 * 60 * 60 * 1000
millis += diff.seconds * 1000
millis += diff.microseconds / 1000
return millis
I hope this helps someone else! :)
From the documentation:
Instance attributes (read-only):
Attribute Value
days Between -999999999 and 999999999 inclusive
seconds Between 0 and 86399 inclusive
microseconds Between 0 and
999999 inclusive
Microseconds never exceed 999,999. Hence your milliseconds never exceed 999.

Find time until a date in Python

What's the best way to find the time until a date. I would like to know the years, months, days and hours.
I was hoping somebody had a nice function. I want to do something like: This comment was posted 2month and three days ago or this comment was posted 1year 5months ago.
datetime module, datetime and timedelta objects, it will give you days and seconds.
In [5]: datetime.datetime(2009, 10, 19) - datetime.datetime.now()
Out[5]: datetime.timedelta(2, 5274, 16000)
In [6]: td = datetime.datetime(2009, 10, 19) - datetime.datetime.now()
In [7]: td.days
Out[7]: 2
In [8]: td.seconds
Out[8]: 5262
You should use dateutil.relativedelta.
from dateutil.relativedelta import relativedelta
import datetime
today = datetime.date.today()
rd = relativedelta(today, datetime.date(2001,1,1))
print "comment created %(years)d years, %(months)d months, %(days)d days ago" % rd.__dict__
Let's asume you have the future datetime in a variable named eta:
(eta - datetime.datetime.now()).total_seconds()
Datetime difference results in a timedelta object, which happens to implement a method named total_seconds. That's it :)
I was looking for something more like this ... which took some hard work to find.
import datetime
SECOND = 1
MINUTE = 60 * SECOND
HOUR = 60 * MINUTE
DAY = 24 * HOUR
MONTH = 30 * DAY
def get_relative_time(dt):
now = datetime.datetime.now()
delta_time = dt - now
delta = delta_time.days * DAY + delta_time.seconds
minutes = delta / MINUTE
hours = delta / HOUR
days = delta / DAY
if delta < 0:
return "already happened"
if delta < 1 * MINUTE:
if delta == 1:
return "one second to go"
else:
return str(delta) + " seconds to go"
if delta < 2 * MINUTE:
return "a minute ago"
if delta < 45 * MINUTE:
return str(minutes) + " minutes to go"
if delta < 90 * MINUTE:
return "an hour ago"
if delta < 24 * HOUR:
return str(hours) + " hours to go"
if delta < 48 * HOUR:
return "yesterday"
if delta < 30 * DAY:
return str(days) + " days to go"
if delta < 12 * MONTH:
months = delta / MONTH
if months <= 1:
return "one month to go"
else:
return str(months) + " months to go"
else:
years = days / 365.0
if years <= 1:
return "one year to go"
else:
return str(years) + " years to go"
may be you want something like this:
import datetime
today = datetime.date.today()
futdate = datetime.date(2016, 8, 10)
now = datetime.datetime.now()
mnight = now.replace(hour=0, minute=0, second=0, microsecond=0)
seconds = (mnight - now).seconds
days = (futdate - today).days
hms = str(datetime.timedelta(seconds=seconds))
print ("%d days %s" % (days, hms))

How do I convert seconds to hours, minutes and seconds?

I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds.
Is there an easy way to convert the seconds to this format in Python?
You can use datetime.timedelta function:
>>> import datetime
>>> str(datetime.timedelta(seconds=666))
'0:11:06'
By using the divmod() function, which does only a single division to produce both the quotient and the remainder, you can have the result very quickly with only two mathematical operations:
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
And then use string formatting to convert the result into your desired output:
print('{:d}:{:02d}:{:02d}'.format(h, m, s)) # Python 3
print(f'{h:d}:{m:02d}:{s:02d}') # Python 3.6+
I can hardly name that an easy way (at least I can't remember the syntax), but it is possible to use time.strftime, which gives more control over formatting:
from time import strftime
from time import gmtime
strftime("%H:%M:%S", gmtime(666))
'00:11:06'
strftime("%H:%M:%S", gmtime(60*60*24))
'00:00:00'
gmtime is used to convert seconds to special tuple format that strftime() requires.
Note: Truncates after 23:59:59
Using datetime:
With the ':0>8' format:
from datetime import timedelta
"{:0>8}".format(str(timedelta(seconds=66)))
# Result: '00:01:06'
"{:0>8}".format(str(timedelta(seconds=666777)))
# Result: '7 days, 17:12:57'
"{:0>8}".format(str(timedelta(seconds=60*60*49+109)))
# Result: '2 days, 1:01:49'
Without the ':0>8' format:
"{}".format(str(timedelta(seconds=66)))
# Result: '00:01:06'
"{}".format(str(timedelta(seconds=666777)))
# Result: '7 days, 17:12:57'
"{}".format(str(timedelta(seconds=60*60*49+109)))
# Result: '2 days, 1:01:49'
Using time:
from time import gmtime
from time import strftime
# NOTE: The following resets if it goes over 23:59:59!
strftime("%H:%M:%S", gmtime(125))
# Result: '00:02:05'
strftime("%H:%M:%S", gmtime(60*60*24-1))
# Result: '23:59:59'
strftime("%H:%M:%S", gmtime(60*60*24))
# Result: '00:00:00'
strftime("%H:%M:%S", gmtime(666777))
# Result: '17:12:57'
# Wrong
This is my quick trick:
from humanfriendly import format_timespan
secondsPassed = 1302
format_timespan(secondsPassed)
# '21 minutes and 42 seconds'
For more info Visit:
https://humanfriendly.readthedocs.io/en/latest/api.html#humanfriendly.format_timespan
The following set worked for me.
def sec_to_hours(seconds):
a=str(seconds//3600)
b=str((seconds%3600)//60)
c=str((seconds%3600)%60)
d=["{} hours {} mins {} seconds".format(a, b, c)]
return d
print(sec_to_hours(10000))
# ['2 hours 46 mins 40 seconds']
print(sec_to_hours(60*60*24+105))
# ['24 hours 1 mins 45 seconds']
A bit off topic answer but maybe useful to someone
def time_format(seconds: int) -> str:
if seconds is not None:
seconds = int(seconds)
d = seconds // (3600 * 24)
h = seconds // 3600 % 24
m = seconds % 3600 // 60
s = seconds % 3600 % 60
if d > 0:
return '{:02d}D {:02d}H {:02d}m {:02d}s'.format(d, h, m, s)
elif h > 0:
return '{:02d}H {:02d}m {:02d}s'.format(h, m, s)
elif m > 0:
return '{:02d}m {:02d}s'.format(m, s)
elif s > 0:
return '{:02d}s'.format(s)
return '-'
Results in:
print(time_format(25*60*60 + 125))
>>> 01D 01H 02m 05s
print(time_format(17*60*60 + 35))
>>> 17H 00m 35s
print(time_format(3500))
>>> 58m 20s
print(time_format(21))
>>> 21s
This is how I got it.
def sec2time(sec, n_msec=3):
''' Convert seconds to 'D days, HH:MM:SS.FFF' '''
if hasattr(sec,'__len__'):
return [sec2time(s) for s in sec]
m, s = divmod(sec, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
if n_msec > 0:
pattern = '%%02d:%%02d:%%0%d.%df' % (n_msec+3, n_msec)
else:
pattern = r'%02d:%02d:%02d'
if d == 0:
return pattern % (h, m, s)
return ('%d days, ' + pattern) % (d, h, m, s)
Some examples:
$ sec2time(10, 3)
Out: '00:00:10.000'
$ sec2time(1234567.8910, 0)
Out: '14 days, 06:56:07'
$ sec2time(1234567.8910, 4)
Out: '14 days, 06:56:07.8910'
$ sec2time([12, 345678.9], 3)
Out: ['00:00:12.000', '4 days, 00:01:18.900']
hours (h) calculated by floor division (by //) of seconds by 3600 (60 min/hr * 60 sec/min)
minutes (m) calculated by floor division of remaining seconds (remainder from hour calculation, by %) by 60 (60 sec/min)
similarly, seconds (s) by remainder of hour and minutes calculation.
Rest is just string formatting!
def hms(seconds):
h = seconds // 3600
m = seconds % 3600 // 60
s = seconds % 3600 % 60
return '{:02d}:{:02d}:{:02d}'.format(h, m, s)
print(hms(7500)) # Should print 02h05m00s
If you need to get datetime.time value, you can use this trick:
my_time = (datetime(1970,1,1) + timedelta(seconds=my_seconds)).time()
You cannot add timedelta to time, but can add it to datetime.
UPD: Yet another variation of the same technique:
my_time = (datetime.fromordinal(1) + timedelta(seconds=my_seconds)).time()
Instead of 1 you can use any number greater than 0. Here we use the fact that datetime.fromordinal will always return datetime object with time component being zero.
dateutil.relativedelta is convenient if you need to access hours, minutes and seconds as floats as well. datetime.timedelta does not provide a similar interface.
from dateutil.relativedelta import relativedelta
rt = relativedelta(seconds=5440)
print(rt.seconds)
print('{:02d}:{:02d}:{:02d}'.format(
int(rt.hours), int(rt.minutes), int(rt.seconds)))
Prints
40.0
01:30:40
Here is a way that I always use: (no matter how inefficient it is)
seconds = 19346
def zeroes (num):
if num < 10: num = "0" + num
return num
def return_hms(second, apply_zeroes):
sec = second % 60
min_ = second // 60 % 60
hrs = second // 3600
if apply_zeroes > 0:
sec = zeroes(sec)
min_ = zeroes(min_)
if apply_zeroes > 1:
hrs = zeroes(hrs)
return "{}:{}:{}".format(hrs, min_, sec)
print(return_hms(seconds, 1))
RESULT:
5:22:26
Syntax of return_hms() function
The return_hms() function is used like this:
The first variable (second) is the amount of seconds you want to convert into h:m:s.
The second variable (apply_zeroes) is formatting:
0 or less: Apply no zeroes whatsoever
1: Apply zeroes to minutes and seconds when they're below 10.
2 or more: Apply zeroes to any value (including hours) when they're below 10.
Here is a simple program that reads the current time and converts it to a time of day in hours, minutes, and seconds
import time as tm #import package time
timenow = tm.ctime() #fetch local time in string format
timeinhrs = timenow[11:19]
t=tm.time()#time.time() gives out time in seconds since epoch.
print("Time in HH:MM:SS format is: ",timeinhrs,"\nTime since epoch is : ",t/(3600*24),"days")
The output is
Time in HH:MM:SS format is: 13:32:45
Time since epoch is : 18793.335252338384 days
You can divide seconds by 60 to get the minutes
import time
seconds = time.time()
minutes = seconds / 60
print(minutes)
When you divide it by 60 again, you will get the hours
In my case I wanted to achieve format
"HH:MM:SS.fff".
I solved it like this:
timestamp = 28.97000002861023
str(datetime.fromtimestamp(timestamp)+timedelta(hours=-1)).split(' ')[1][:12]
'00:00:28.970'
The solutions above will work if you're looking to convert a single value for "seconds since midnight" on a date to a datetime object or a string with HH:MM:SS, but I landed on this page because I wanted to do this on a whole dataframe column in pandas. If anyone else is wondering how to do this for more than a single value at a time, what ended up working for me was:
mydate='2015-03-01'
df['datetime'] = datetime.datetime(mydate) + \
pandas.to_timedelta(df['seconds_since_midnight'], 's')
I looked every answers here and still tried my own
def a(t):
print(f"{int(t/3600)}H {int((t/60)%60) if t/3600>0 else int(t/60)}M {int(t%60)}S")
Results:
>>> a(7500)
2H 5M 0S
>>> a(3666)
1H 1M 6S
Python: 3.8.8
division = 3623 // 3600 #to hours
division2 = 600 // 60 #to minutes
print (division) #write hours
print (division2) #write minutes
PS My code is unprofessional

Categories