in reply to Date/Time Manipulation

Looking for a simple (hopefully) way of subtracting one hour from date - time in a file.

Simple, you say?

perl -pe 's/ (\d\d)/sprintf(" %2.2i",$1-1)/e;'

Replies are listed 'Best First'.
Re^2: Date/Time Manipulation
by Anonymous Monk on May 25, 2016 at 14:01 UTC

    Thank you hippo

    After surrounding that with variable definitions, file paths, file open/close and prints to a new file in a Perl script, I am a VERY HAPPY CAMPER.

    Not sure how it works; will explore that.

      Forgot to log in, RobertJ. Again thanks.

        Be aware that you might not be such a happy camper if the times fall within the hour after midnight! That code matches and captures, in the special variable $1, the two digits following a space, i.e. the hour value. It then executes (e modifier) the sprintf command in the substitution to replace the hour with a decremented value ($1 - 1). The q{ %2.2i} is the format specifier; q{ %02d} would also work. This method will break down if the hour is zero.

        The simple way.

        $ perl -Mstrict -Mwarnings -E ' my $dateStr = q{2016-05-16 00:51:07}; $dateStr =~ s{ (\d\d)}{ sprintf q{ %2.2i}, $1 - 1 }e; say $dateStr;' 2016-05-16 -01:51:07 $

        A little more robust.

        $ perl -MTime::Piece -MTime::Seconds -Mstrict -Mwarnings -E ' my $dateStr = q{2016-05-16 00:51:07}; my $dateFmt = q{%Y-%m-%d %H:%M:%S}; my $tp = Time::Piece->strptime( $dateStr, $dateFmt ); $tp -= ONE_HOUR; say $tp->strftime( $dateFmt );' 2016-05-15 23:51:07 $

        I hope this is of interest.

        Cheers,

        JohnGG

        OK I have been looking at that statement

        $stuff =~ s/ (\d\d)/sprintf(" %2.2i",$1-1)/e;

        I have poured over my Perl O'Reilly book and am still clueless. Since the input lines look like this

        2016-05-16 10:51:07 random text

        How does the expression pick out the hours versus any other two digits?

        Then what does the sprintf do? I'm willing to learn but would need a starting point.