Best way to convert number of minutes to hh:mm AM/PM?

Cameron Simpson cs at zip.com.au
Fri Mar 1 20:22:57 EST 2013


On 01Mar2013 16:12, andydtaylor at gmail.com <andydtaylor at gmail.com> wrote:
| I need to create a list of equally spaced times (as in hh:mm
| AM/PM) within a day to loop through. Having selected 30 minute
| intervals I figured I could:
| 
| * Create a list from 1 to 48
| * Multiply each value by 30
| * Convert minutes to a time. datetime.timedelta seems to do this,
|   but it's not a full timestamp which means strftime can't format me
|   a time with am/pm.
| 
| can anyone suggest a good approach to use? Ultimately I'd like
| to generate an equivalent to this text/format:'2:30 pm'

If they're just minutes to hours and minutes you don't need datetime;
it is most useful to handle the many complexities of calendars.

There are 60 minutes to an hour. So something like (untested):

  for n in range(0,48): # counts 0..47 inclusive
    minutes = 30 * (n + 1)
    hours = minutes // 60
    minutes = minutes % 60
    if hours >= 12:
      ampm = 'pm'
      hours -= 12
    else:
      ampm = 'am'
    if hours < 1:
      hours += 12
    print '%02d:%02d %s" % (hours, minutes, ampm)

Cheers,
-- 
Cameron Simpson <cs at zip.com.au>

The Borg assimilated my race and all I got was this lousy tagline.
        - Cath Lawrence <Cath_Lawrence at premium.com.au>



More information about the Python-list mailing list