我有一个制表符分隔文件,其中每个记录具有12小时格式的时间戳记字段:
mm/dd/yyyy hh:mm:ss [AM|PM].
我需要快速将这些字段转换为24小时的时间:
mm/dd/yyyy HH:mm:ss.
这样做最好的方法是什么?我正在Windows平台上运行,除了通常的Windows工具之外,我还可以访问sed,awk,perl,python和tcl.
解决方法
使用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\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 – > 00:01
> 12:01 PM – > 12:01
> 01:30 AM – > 01:30
> 01:30 PM – > 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);
只是一个测试…可能更整洁