KBD

Keith Devens .com

Saturday, September 6, 2008 Flag waving
Linux is only free if your time has no value – Jamie Zawinski

Archive: February 02, 2006

← January 31, 2006February 05, 2006 →

Daily link icon Thursday, February 2, 2006

How to programatically convert stupid 12 hour timestamps to 24 hours

Every time I have to manually parse a 12 hour timestamp (with "am" and "pm") into a 24 hour format I have to think about it to get the logic right. Now I won't have to again:

def twelveto24(hr, per):
    if hr == 12 and per == 'a': return 0
    if hr != 12 and per == 'p': return hr+12
    return hr

hours = range(1,13)
hours = zip(hours,['a']*12)+zip(hours,['p']*12)

for hr, per in hours:
    print twelveto24(hr, per),

#results
1 2 3 4 5 6 7 8 9 10 11 0 13 14 15 16 17 18 19 20 21 22 23 12

Update: For the hell of it, here's the Perl code I wrote to do the thing I actually had to do:

sub getTimestamp{
    #02/01/2006,05:06:04am
    $_[0] =~ m@\[(\d+)/(\d+)/(\d+),(\d+):(\d+):(\d+)([aApP])[mM]\]@;
    return "$3-$1-$2 ".sprintf("%02d",twelveto24($4,lc($7))).":$5:$6";
}

sub twelveto24{
    ($hr, $per) = @_;
    return 0 if($hr == 12 and $per eq 'a');
    return $hr+12 if($hr != 12 and $per eq 'p');
    return $hr;
}

print getTimestamp("[02/01/2006,12:06:04am]");
#2006-02-01 00:06:04
← January 31, 2006February 05, 2006 →
September 2008
SunMonTueWedThuFriSat
 123456
78910111213
14151617181920
21222324252627
282930 



RSS feed RSS feed for Keith's Weblog
Atom feed Atom feed for Keith's Weblog
Weblog archive
Recent comments
  on 5 posts

Recent comments XML

new⇒I hate ASP.NET

CF, why pick that piece of trash?​Cold Confusion. Is it finally​really a OO...

ColdConfusion: Sep 5, 8:36pm

Maps of Iraq

This is for Linda, I will be​visiting that site some time in the​near futur...

Bob: Sep 5, 1:20pm

Girls, please don't get breast implants

Well alright I just read my above​comment and I wanted to add​this...I shou...

76.66.140.8: Sep 4, 7:31pm

Spider solitaire

I don't think the question was​necessarily if there are unbeatable​games.  ...

Jared: Sep 4, 12:44pm

Convert Pantone Colors to RGB and Hex - Color Conversion Chart

The colors on those website don't​seem to relate to the pantone data​we hav...

blah: Sep 3, 10:12am

Generated in about 0.157s.

(Used 7 db queries)

mobile phone