Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

datetime - Convert 12-hour date/time to 24-hour date/time

I have a tab delimited file where each record has a timestamp field in 12-hour format:

mm/dd/yyyy hh:mm:ss [AM|PM].

I need to quickly convert these fields to 24-hour time:

mm/dd/yyyy HH:mm:ss.

What would be the best way to do this? I'm running on a Windows platform, but I have access to sed, awk, perl, python, and tcl in addition to the usual Windows tools.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using Perl and hand-crafted regexes instead of facilities like strptime:

#!/bin/perl -w
while (<>)
{
    # for date times that don't use leading zeroes, use this regex instead:
    # (?:d{1,2}/d{1,2}/d{4} )(d{1,2})(?::dd:dd) (AM|PM)
    while (m%(?:dd/dd/d{4} )(dd)(?::dd:dd) (AM|PM)%)
    {
        my $hh = $1;
        $hh -= 12 if ($2 eq 'AM' && $hh == 12);
        $hh += 12 if ($2 eq 'PM' && $hh != 12);
        $hh = sprintf "%02d", $hh;
        # for date times that don't use leading zeroes, use this regex instead:
        # (d{1,2}/d{1,2}/d{4} )(d{1,2})(:dd:dd) (?:AM|PM)
        s%(dd/dd/d{4} )(dd)(:dd:dd) (?:AM|PM)%$1$hh$3%;
    }
    print;
}

That's very fussy - but also converts possibly multiple timestamps per line.

Note that the transformation for AM/PM to 24-hour is not trivial.

  • 12:01 AM --> 00:01
  • 12:01 PM --> 12:01
  • 01:30 AM --> 01:30
  • 01:30 PM --> 13:30

Now tested:

perl ampm-24hr.pl <<!
12/24/2005 12:01:00 AM
09/22/1999 12:00:00 PM
12/12/2005 01:15:00 PM
01/01/2009 01:56:45 AM
12/30/2009 10:00:00 PM
12/30/2009 10:00:00 AM
!

12/24/2005 00:01:00
09/22/1999 12:00:00
12/12/2005 13:15:00
01/01/2009 01:56:45
12/30/2009 22:00:00
12/30/2009 10:00:00

Added:

In What is a Simple Way to Convert Between an AM/PM Time and 24 hour Time in JavaScript, an alternative algorithm is provided for the conversion:

$hh = ($1 % 12) + (($2 eq 'AM') ? 0 : 12);

Just one test...probably neater.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...