Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Perl Monks,

I am running into a small problem in my script, I am trying to work out the average time of something. Here is what I have done:

I use perl time() function to get the epoch seconds, i then update this whenever say an event happens by doing this:
#$restime is called from the database, which is the previos total. ...snip... $current_time = time(); $res_time = $logtime - $current_time; $newtime = $res_time+$stime; ...snip... #I then update the database by inserting new time, next time the numbe +r will grow again etc..
Now what I want to do is convert $newtime to something like 6 hours 4 minute and 30 seconds

Is this possible?

Replies are listed 'Best First'.
Re: time ()
by hakkr (Chaplain) on Dec 05, 2001 at 19:29 UTC
    use the localtime function
    ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($newtime);
      Using localtime is fine if $newtime is a real time value. But from the description I assume it is a delta time. ie a value like 21870. Becasue of the zone offset, localtime would produce different results around the world. However gmtime() will always give what is wanted.

      ($seconds,$minutes,$hours,$days) = (gmtime($newtime))[0,1,2,7];
Re: time ()
by clintp (Curate) on Dec 05, 2001 at 19:49 UTC
    So essentially: you're subtracting the start time from the current time, both expressed in seconds. The result is a pile of seconds that then need to be translated to days, hours, minutes and leftover seconds. Right?

    The DateCalc function in the Date::Manip module would do this. Beware, this is a heavyweight module. It might just be quicker to divide by 86400 (days), take the remainder and divide by 60*60 (hours), take the remainder and divide by 60 (minutes), and what's left is seconds.

      Implementers should note that a simple solution like this, while simple and usually perfectly adequate, will break with 'day', 'month' or 'year' labels across:
      • Daylight Savings Time boundaries
      • Month boundaries (given that months have varying days)
      • Leap Year boundaries
Re: time ()
by blakem (Monsignor) on Dec 06, 2001 at 01:06 UTC