[NCLUG] perl datestring to timestamp conversion ?

Gabriel Somlo somlo at acns.colostate.edu
Mon Jan 10 11:24:34 MST 2005


Hi,

I'm trying to write a perl script that receives a bunch of lines
containing time stamps formatted like so:

	YYYY-MM-DD hh:mm:ss [utc]

Some of them have 'utc' at the end (and that means they're in UTC :)
and some don't (and they are to be considered local time for wherever
this script runs).

I need to convert these into the official "seconds since '00:00:00
1970-01-01 UTC'" timestamp value.

I've tried POSIX::mktime, like so:

my $timestamp = POSIX::mktime( $ss, $mm, $hh,
                               $DD, $MM-1, $YYYY-1900,
                               0, 0, -1 );

and this handles all local time conversions fine. The -1 for the last
argument is to get it to automagically handle daylight savings time.


How can I get it to switch between local time (which is all it does
now) to UTC, so I can handle the lines that are given in UTC ?

Right now, I'm doing it like so:

	my $utc = ( $is_utc_entry ) ? 'utc' : '';

	my $timestamp = qx/date -d "$YYYY-$MM-$DD $hh:$mm:$ss $utc" +%s/;

and let the 'date' program handle it. However, this script should be
portable, and run on weird things other than linux, where 'date'
doesn't have the %s option. Also, it would be nice if I didn't have to
ask various admins to install any extra perl modules :) 

Thanks a ton for any ideas !

Gabriel



More information about the NCLUG mailing list