perl - Converting string to datetime MMM DD YYYY HH:MMAM to YYYY-MM-DD HH:MM:SS -


feb   2 2016 12:00am feb 15 2015 05:00pm  

would convert above data 'yyyy-mm-dd tt:tt:tt' format, ideally:

2016-02-02 00:00:00

here's i've tried using substitution convert it. reason have 2 different ones because when bcp out data text file dates single digit uses space instead of 0 in front of it:

s/feb  (\d{1}) (\d{4}) (\d{2})(\:\d{2})am/2-$1-2 $3$4/g;  s/feb (\d{2}) (\d{4}) (\d{2})(\:\d{2})am/2-$1-2 $3$4/g; 

also not sure how go converting time military time , there more efficient way 12 months rather have 12 lines of substitution of them, in case there 24.

the time::piece module convenient sort of thing

the strptime class method takes date-time string , format specification uses parse string create new object. meanwhile strftime method return date-time string according format specification

use strict; use warnings 'all';  use time::piece ();  while ( <data> ) {     chomp;     $new_dt = time::piece->strptime($_, '%b %d %y %h:%m%p')->strftime('%y-%m-%d %h:%m:%s');     printf "%s --> %s\n", $_, $new_dt; }  __data__ feb 2 2016 12:00am feb 15 2015 05:00pm 

output

feb 2 2016 12:00am --> 2016-02-02 00:00:00 feb 15 2015 05:00pm --> 2015-02-15 17:00:00 

Comments