[Tutor] time(duration) formats & basic time math query
Kent Johnson
kent37 at tds.net
Thu Jul 6 12:28:41 CEST 2006
kevin parks wrote:
> I have been handed a huge number of documents which have hundreds of
> pages of times and durations, all calculated and notated by several
> different people over the course of many years. Sadly, no made any
> guidelines at all about how this work would proceed and all the
> documenters had their own ideas about how times/durations would be
> specified so the doc are a mess. Furthermore the person i work for
> changes her mind every 15 minutes so i have no idea what she will
> want at any given moment. This sounds to me like a job for Python
> <hee hee>
>
Yep!
> Essentially, I am trying to do 2 things:
>
> move fluidly between different duration formats (take any, specify
> and display any). Such as:
>
> pure miliseconds
> seconds. msec
> mm:ss.msec
> hh:mm:ss.msec
>
> So the input doc would be grepped for times and i could just
> uncomment the line i need and get he format my boss wants at this
> particular moment.
> So a recording that is 71 minutes and 33 seconds could be printed as:
> 4293 seconds
> 71:33.0000
> 01:11.33.0000 or whatever....
>
> also i need to be able to adjust start times, durations, and end
> times which means doing a little time math.
> Like if a recording is 71 minute and 33 seconds.. but there are
> several sonic events in that recording and i
> need to specify the duration, or start time etc of those individual
> events... then i need to subtract... Additionally i
> know that i will need to subtract pure minutes from an hh:mm format....
>
> I having a real hard time getting my head round the labyrinthian
> datetime module in the docs (i am guessing
> that this is what i should use). I wonder if anyone could give me a
> hand and point me in the right direction.
time.strptime() can help with the parsing, though it doesn't handle
milliseconds so you will have to do that part yourself. You can
construct a datetime.datetime object from the output of strptime(). Use
datetime.timedelta to do the offsets. Use datetime.strftime() to format
the output. For example:
In [1]: from datetime import datetime, timedelta
In [2]: import time
In [6]: time.strptime('01:11.33', '%H:%M.%S')
Out[6]: (1900, 1, 1, 1, 11, 33, 0, 1, -1)
In [7]: time.strptime('01:11.33', '%H:%M.%S')[:6]
Out[7]: (1900, 1, 1, 1, 11, 33)
In [11]: td=timedelta(minutes=2, seconds=5)
In [15]: d=datetime(*time.strptime('01:11.33', '%H:%M.%S')[:6])
In [16]: d
Out[16]: datetime.datetime(1900, 1, 1, 1, 11, 33)
In [17]: d+td
Out[17]: datetime.datetime(1900, 1, 1, 1, 13, 38)
In [18]: (d+td).strftime('%H:%M.%S')
Out[18]: '01:13.38'
Kent
More information about the Tutor
mailing list