11

我有一个制表符分隔的文件,其中每条记录都有一个 12 小时格式的时间戳字段:

mm/dd/yyyy hh:mm:ss [上午|下午]。

我需要快速将这些字段转换为 24 小时制:

mm/dd/yyyy HH:mm:ss。

最好的方法是什么?我在 Windows 平台上运行,但除了常用的 Windows 工具之外,我还可以访问 sed、awk、perl、python 和 tcl。

4

8 回答 8

12

使用 Perl 和手工制作的正则表达式而不是 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;
}

这非常麻烦 - 但也可能每行转换多个时间戳。

请注意,将 AM/PM 转换为 24 小时制并非易事。

  • 上午 12:01 --> 00:01
  • 下午 12:01 --> 12:01
  • 上午 01:30 --> 01:30
  • 下午 1:30 --> 13:30

现在测试:

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

补充

什么是在 JavaScript 中转换 AM/PM 时间和 24 小时时间的简单方法中,为转换提供了另一种算法:

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

只有一个测试......可能更整洁。

于 2009-01-13T18:10:27.077 回答
12

这是python中的单行代码:

time.strftime('%H:%M:%S', time.strptime(x, '%I:%M %p'))

例子:

>>> time.strftime('%H:%M:%S', time.strptime('08:01 AM', '%I:%M %p'))
'08:01:00'
>>> time.strftime('%H:%M:%S', time.strptime('12:01 AM', '%I:%M %p'))
'00:01:00'
于 2010-12-08T16:04:40.380 回答
4

以某种方式使用 Python 的 datetime 模块:

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")

未经测试的代码,没有错误检查。它还在开始之前读取内存中的整个输入文件。(我知道有很多改进的空间,比如声明......如果有人喜欢添加一些东西,我会将其设为社区 wiki 条目)

于 2009-01-13T18:07:30.140 回答
2

要仅转换小时字段,在 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)
于 2009-10-23T05:36:43.243 回答
0

这个想法可能太简单了,但是为什么不将其导入excel,选择整列并更改日期格式,然后重新导出为制表符分隔文件呢?(我没有对此进行测试,但这对我来说听起来很合乎逻辑:)

于 2009-01-13T18:34:22.253 回答
0

在这里,我已将 24 小时制转换为 12 小时制。尝试使用此方法解决您的问题。

    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 
于 2009-03-10T08:49:47.980 回答
0

在 Python 中:将 12 小时时间转换为 24 小时时间

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])
于 2016-09-19T18:27:37.593 回答
-1

由于您有多种语言,我将建议以下算法。

1 检查时间戳是否存在“PM”字符串。

2a 如果 PM 不存在,只需将时间戳转换为日期时间对象并继续。

2b 如果 PM 确实存在,则将时间戳转换为日期时间对象,加上 12 小时,然后继续。

于 2009-01-13T18:04:33.843 回答