[NCLUG] perl datestring to timestamp conversion ?
Tkil
tkil at scrye.com
Mon Jan 10 17:19:07 MST 2005
>>>>> "Gabriel" == Gabriel Somlo <somlo at acns.colostate.edu> writes:
Gabriel> I'm trying to write a perl script that receives a bunch of
Gabriel> lines containing time stamps formatted like so:
Gabriel> YYYY-MM-DD hh:mm:ss [utc]
Gabriel> Some of them have 'utc' at the end (and that means they're in UTC :)
Gabriel> and some don't (and they are to be considered local time for wherever
Gabriel> this script runs).
Gabriel> I need to convert these into the official "seconds since
Gabriel> '00:00:00 1970-01-01 UTC'" timestamp value.
search.cpan.org
Look for "date" and "parse".
Surprisingly enough, there's Date::Parse. :)
(Some of the other Date:: modules, like Date::Calc and a few others,
have various skills at parsing formats, but Date::Parse does the trick
for me...)
To archive off mailing list posts, I use something like this:
| use Date::Parse qw(str2time);
|
| [...]
|
| while (<F>)
| {
| if (/^Date:\s+(.*)$/)
| {
| $date = $1;
| last LINE;
| }
| }
| close F
| or warn "problem closing '$file': $!";
|
| unless ($date)
| {
| # i considered using the date from the last file, but there's no
| # guarantee that they will be in sequential order. this should be
| # rare enough to where i can just deal with them individually.
| warn "no date in '$file', skipping";
| next FILE;
| }
|
| print STDERR " date='$date'" if $DEBUG > 1;
|
| $@ = '';
|
| my $time_t = eval { str2time($date); };
|
| if ($@)
| {
| warn "str2time barfed on \"$date\": $@";
| next FILE;
| }
|
| unless (defined $time_t)
| {
| warn "couldn't parse '$date' in '$file', skipping";
| next FILE;
| }
|
| print STDERR "\n time_t=$time_t" if $DEBUG > 1;
|
| # pick out the year and month from the "localtime" return values.
| # adjust them appropriately, then format them:
| my ($y, $m) = (localtime($time_t))[5, 4];
| $y += 1900;
| $m += 1;
| my $yyyy_mm = sprintf "%04d-%02d", $y, $m;
|
| print STDERR " dest=$yyyy_mm\n" if $DEBUG > 1;
Good luck,
t.
More information about the NCLUG
mailing list