[Tutor] How to convert seconds to hh:mm:ss format
Martin A. Brown
martin at linux-ip.net
Thu Feb 16 23:21:29 CET 2012
Welcome to the joys of time and date handling.
: userName = raw_input("Enter your name ")
: print "hi " + userName + ". \n "
: seconds = input("Enter the number of seconds since midnight:")
: hours = seconds/3600
: hoursRemain = hours%60
: minutes = hoursReamain/60
: secondsRemain = minutes%60
: print "hours: " + "minutes: " + "seconds"
:
: I'm going to be crazy.
In fact, yes, you probably will. This is one of those wonderful
places where you probably really want to look into what a library
can do for you. There are many, but I'll just start with the
standard library called time.
Read the documenation on the time module:
http://docs.python.org/library/time.html
Here's a simple example of getting the time right now, and
presenting in in a variety of ways. I give '%T' as the example you
asked for, and then, I make up a nonstandard example to show how
rich the format operators are when using strftime().
>>> import time
>>> time.gmtime()
time.struct_time(tm_year=2012, tm_mon=2, tm_mday=16, tm_hour=22, tm_min=2, tm_sec=26, tm_wday=3, tm_yday=47, tm_isdst=0)
>>> time.strftime('%T',time.gmtime())
'22:02:28'
>>> time.strftime('%R %A %B %d, %Y',time.gmtime())
'22:02 Thursday February 16, 2012'
>>> time.strftime('%R %A %B %d, %Y',time.localtime())
'17:02 Thursday February 16, 2012'
Now, you will probably need to think carefully about whether you
want localtime() or gmtime(). You will probably need to consider
whether you need to do any date math.
: Please give me a hand. Thank you very much.
Play with strftime(). This is a feature of many languages and
programming environments. It should be able to produce most (if not
all) output formats you probably need.
Now, you specifically asked about how to deal with adding and
subtracting dates and times. For this, consider the datetime
module/library. Yes, there's a small bit of overlap...notably that
you can also use strftime() on datetime objects.
http://docs.python.org/library/datetime.html
>>> import datetime
>>> now = datetime.datetime.now()
>>> twohrsago = datetime.timedelta(minutes=120)
>>> now
datetime.datetime(2012, 2, 16, 17, 15, 46, 655472)
>>> now + twohrsago
datetime.datetime(2012, 2, 16, 19, 15, 46, 655472)
>>> then = now + twohrsago
>>> then.strftime('%F-%T')
'2012-02-16-19:15:46'
I would add my voice to Ramit Prasad's voice and strongly suggest
using the date and time handling tools available in libraries,
rather than try to build your own.
Good luck,
-Martin
--
Martin A. Brown
http://linux-ip.net/
More information about the Tutor
mailing list