X: I want to write timestamps to a text file in a reasonably human-friendly format and then read them back, getting the same epoch second for comparison with localtime.

Y: my first attempt with Time::Piece:

use strict; use warnings; use Time::Piece; use feature 'say'; my $fmt = '%d %b %Y %T %Z'; say localtime->strftime; say localtime->strftime($fmt); my $str = '03 Sep 2022 16:10:17 GMT Daylight Time'; my $strtime = Time::Piece->strptime($str, $fmt); say localtime->epoch; say $strtime->epoch;

This returns:

Sat, 03 Sep 2022 16:10:35 GMT Daylight Time 03 Sep 2022 16:10:35 GMT Daylight Time Garbage at end of string in strptime: Daylight Time at C:/Strawberry/ +perl/lib/Time/Piece.pm line 598. Perhaps a format flag did not match the actual input? at C:/Strawberry +/perl/lib/Time/Piece.pm line 598. 1662217835 1662221417

This is out by the timezone offset. The docs tell me to look at https://www.unix.com/man-page/FreeBSD/3/strftime/, which says that %z will be treated as a numerical offset. For me, this gives the same as upper case Z, although I can't rule out the influence of Windows on this. DateTime says it won't parse dates and gives no indication I could see of how to handle localtime.

I'd be happy with UTC, but Time::Piece does not seem to support it, which is why I think I may have an XY problem. I can't believe that no-one has invented this wheel, but my searches have been fruitless and all the wheels I have tried seem square. I know that clocks moving back at the end of next month will bite me. All help gratefully received.

Regards,

John Davies


In reply to [Solved] Reading a timestamp and getting the written value by davies

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.