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
new⇒I hate ASP.NET
CF, why pick that piece of trash?Cold Confusion. Is it finallyreally a OO...
ColdConfusion: Sep 5, 8:36pm