将12小时日期/时间转换为24小时日期/时间

时间:2009-01-13 17:59:28

标签: datetime text-files

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

  

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

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

  

mm / dd / yyyy HH:mm:ss。

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

8 个答案:

答案 0 :(得分: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 AM - &gt; 00:01
  • 12:01 PM - &gt; 12:01
  • 01:30 AM - &gt; 01:30
  • 01:30 PM - &gt; 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

What is a Simple Way to Convert Between an AM/PM Time and 24 hour Time in JavaScript中,为转换提供了另一种算法:

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

只需一次测试......可能更整洁。

答案 1 :(得分:10)

在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'

答案 2 :(得分:4)

使用Pythons 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条目)

答案 3 :(得分:1)

要在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)

答案 4 :(得分:0)

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

答案 5 :(得分: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 

答案 6 :(得分: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])

答案 7 :(得分:-1)

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

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

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

2b如果PM确实存在,请将时间戳转换为datetime对象,添加12小时,然后继续。

相关问题