将 12 小时制日期/时间转换为 24 小时制日期/时间 [英] Convert 12-hour date/time to 24-hour date/time
问题描述
我有一个制表符分隔的文件,其中每条记录都有一个 12 小时格式的时间戳字段:
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].
mm/dd/yyyy hh:mm:ss [AM|PM].
我需要快速将这些字段转换为 24 小时制:
I need to quickly convert these fields to 24-hour time:
mm/dd/yyyy HH:mm:ss.
mm/dd/yyyy HH:mm:ss.
这样做的最佳方法是什么?我在 Windows 平台上运行,但除了常用的 Windows 工具外,我还可以使用 sed、awk、perl、python 和 tcl.
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.
推荐答案
使用 Perl 和手工制作的正则表达式代替 strptime 之类的工具:
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.
请注意,将 AM/PM 转换为 24 小时制并非易事.
Note that the transformation for AM/PM to 24-hour is not trivial.
- 上午 12:01 --> 00:01
- 下午 12:01 --> 12:01
- 01:30 AM --> 01:30
- 下午 01: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 小时时间之间转换的简单方法是什么,为转换提供了一种替代算法:
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.
这篇关于将 12 小时制日期/时间转换为 24 小时制日期/时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!