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

2019-01-04 13:57发布

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.

8条回答
霸刀☆藐视天下
2楼-- · 2019-01-04 14:06

Here i have converted 24 Hour system to 12 Hour system. Try to use this method for your problem.

    DateFormat fmt = new SimpleDateFormat("yyyyMMddHHssmm");

    try {
        Date date =fmt.parse("20090310232344");

        System.out.println(date.toString());
        fmt = new SimpleDateFormat("dd-MMMM-yyyy hh:mm:ss a ");
        String dateInString = fmt.format(date);
        System.out.println(dateInString);


    } catch (Exception e) {
        System.out.println(e.getMessage());
    } 

  RESULT:  
   Tue Mar 10 23:44:23 IST 2009   
   10-March-2009 11:44:23 PM 
查看更多
爷的心禁止访问
3楼-- · 2019-01-04 14:06

Since you have multiple languages, I'll suggest the following algorithm.

1 Check the timestamp for the existence of the "PM" string.

2a If PM does not exist, simply convert the timestamp to the datetime object and proceed.

2b If PM does exist, convert the timestamp to the datetime object, add 12 hours, and proceed.

查看更多
ら.Afraid
4楼-- · 2019-01-04 14:07

In Python: Converting 12hr time to 24hr time

import re
time1=input().strip().split(':')
m=re.search('(..)(..)',time1[2])
sec=m.group(1)
tz=m.group(2)  
if(tz='PM'):
     time[0]=int(time1[0])+12
     if(time1[0]=24):
            time1[0]-=12
     time[2]=sec         
else:
     if(int(time1[0])=12):
            time1[0]-=12
     time[2]=sec


print(time1[0]+':'+time1[1]+':'+time1[2])
查看更多
ら.Afraid
5楼-- · 2019-01-04 14:15

Use Pythons datetime module someway like this:

import datetime

infile = open('input.txt')
outfile = open('output.txt', 'w')
for line in infile.readlines():
  d = datetime.strptime(line, "input format string")
  outfile.write(d.strftime("output format string")

Untested code with no error checking. Also it reads the entire input file in memory before starting. (I know there is plenty of room for improvements like with statement...I make this a community wiki entry if anyone likes to add something)

查看更多
何必那么认真
6楼-- · 2019-01-04 14:16

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})(?::\d\d:\d\d) (AM|PM)
    while (m%(?:\d\d/\d\d/\d{4} )(\d\d)(?::\d\d:\d\d) (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})(:\d\d:\d\d) (?:AM|PM)
        s%(\d\d/\d\d/\d{4} )(\d\d)(:\d\d:\d\d) (?: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.

查看更多
干净又极端
7楼-- · 2019-01-04 14:18

To just convert the hour field, in python:

def to12(hour24):
    return (hour24 % 12) if (hour24 % 12) > 0 else 12

def IsPM(hour24):
    return hour24 > 11

def to24(hour12, isPm):
    return (hour12 % 12) + (12 if isPm else 0)

def IsPmString(pm):
    return "PM" if pm else "AM"

def TestTo12():    
    for x in range(24):
        print x, to12(x), IsPmString(IsPM(x))

def TestTo24():
    for pm in [False, True]:
        print 12, IsPmString(pm), to24(12, pm)
        for x in range(1, 12):
            print x, IsPmString(pm), to24(x, pm)
查看更多
登录 后发表回答