2015-07-10 20 views
0

我有一个这样的日期/时间:2015-07-31T13:30:00.000 + 01:00 我想将其转换为使用Perl和时间:: Piece-> strptime如何使用Perl将未知的日期/时间格式转换为正常?

正常的日期和时间这里是我的代码:

sub changeDateFormat { 
    my ($date, $fromFormat, $toFormat) = (@_); 
    return Time::Piece->strptime($date, $fromFormat)->strftime($toFormat); 
} 

召唤:

print changeDateFormat($that_date, '%Y-%m-%dT%H:%M:%S.%N+%z', '%Y:%m:%d'); 

我认为.000是纳米秒和01.00代表时区。 但给定的代码给出了这样: 错误解析在/usr/lib64/perl5/Time/Piece.pm线470

任何帮助表示赞赏时间。

+0

见['日期时间::格式:: Strptime'](H ttps://metacpan.org/pod/DateTime :: Format :: Strptime)..它同时具有'%N'和'%z' .. –

+1

该格式被称为ISO 8601日历日期和时间扩展格式的区域指示符。 [Time :: Moment-> from_string](https://metacpan.org/pod/distribution/Time-Moment/lib/Time/Moment.pod#from_string)可用于解析它。 – chansen

回答

1

我觉得有几个问题。

%N不在我的strftime联机帮助页中。所以这可能无法正常工作。

%z - 我很确定+01:00无效。

%z  The +hhmm or -hhmm numeric timezone (that is, the hour and 
      minute offset from UTC). (SU) 

这工作虽然:

my $date = '2015-07-31T13:30:00+0100'; 
my $fromFormat = '%Y-%m-%dT%H:%M:%S%z'; 
print Time::Piece->strptime($date, $fromFormat); 

所以我建议 - 除非你的毫秒很重要 - 你可以只剥除通过正则表达式的,同样的时区。 (而且它们很重要,我不认为Time::Piece无论如何都无法解析ms)

如果您倾向于使用正则表达式来“更正”您的输入日期,那么您可以使用正则表达式。我不确定是否符合你的使用情况,但:

$date =~ s/\+(\d{2}):(\d{2})$/+$1$2/; 
$date =~ s/\.\d{3}+/+/; 
1

您可以使用Time::Piecestrptime和手动添加的时区,如图this answer,或者你可以尝试使用DateTime::Format::Strptime代替:

use feature qw(say); 
use strict; 
use warnings; 
use DateTime::Format::Strptime; 

my $timestamp = '2015-07-31T13:30:00.000+0100'; 
my $strp = DateTime::Format::Strptime->new(
    pattern => '%Y-%m-%dT%H:%M:%S.%N%z' 
); 

my $dt = $strp->parse_datetime($timestamp); 

say $dt->strftime('%Y:%m:%d'); 

输出:

2015:07:31 
+0

那么'%N'是否在那个工作? – Sobrique

1
use DateTime; 
use DateTime::Format::ISO8601; 

use DateTime::Format::Strptime; 

my $string = '2015-07-31T13:30:00.000+01:00'; 
my $date = DateTime::Format::ISO8601->parse_datetime($string); 
die "Error" unless $date; 

my $formatter = new DateTime::Format::Strptime(pattern => '%Y-%m-%d %T'); 
$date->set_formatter($formatter); 
print "$date\n"; 
相关问题