Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

Date and time difference

by Anonymous Monk
on Nov 17, 2010 at 11:28 UTC ( #871978=perlquestion: print w/replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Iam having one doubt by taking the time difference. currently iam having two variable previous and current. the Date is formatted like 'YearMonthDateHour'.


previous = '10111623';

current = '10111705';

I want to take the difference between the two date;


10111624,10111701, 10111702,10111703, 10111704

is there any special builtin function to generate like this. Regards, Balaji S

Replies are listed 'Best First'.
Re: Date and time difference
by roboticus (Chancellor) on Nov 17, 2010 at 13:30 UTC

    While there are many date & time packages available on CPAN, for my purposes, I generally just store times as returned by time() (seconds since 1970/01/01 00:00:00 IIRC). Then taking the difference is a simple subtraction. Of course, you'll need to format the results when you're done. But I typically do something like:

    my $start=time; # ... long processing job goes here... my $dur = time - $start; # Print out in appropriate format: print "Job took $dur seconds\n"; # For longer jobs, I often use one of: printf "Job took %5.2 minutes\n", $dur/60.0; printf "Job took %5.2 hours\n", $dur/(60*60.0); printf "Job took %5.2 days\n", $dur/(24*60*60.0); printf "Job took %5.2 weeks\n", $dur/(7*24*60*60.0); # etc.

    Pretty simple and adequate for what I do. If I cared for more accuracy or features, I'd check out one of the Date modules on CPAN.


    I have a fancier formatting module to show in format "Days HH:MM:SS", but the margin is too small for me to note it here. (Actually, it's on my server at home, and I haven't brought into work with me yet. It's on my TODO list.)

Re: Date and time difference
by Ratazong (Monsignor) on Nov 17, 2010 at 12:12 UTC
    What about the following approach:
    • use Date::Calc for convenient date-calculations, including leap-year-support etc.
    • extract year, month, day ... from your dates (e.g. by using a regex)
    • increase your date by one in a loop (using Add_Delta_DHMS)
      • if the new date is equal to the end-date, end the program
      • else transform the new date in your format, print it and continue your loop
    HTH, Rata
Re: Date and time difference
by JavaFan (Canon) on Nov 17, 2010 at 12:16 UTC
    Hour 24? That's odd. You sure you don't want 10111700? OTOH, while parts of the world where using 24 hours in a day in the year 10 AD, I'm not quite sure they numbered their hours up to 23 (or rather 24, as 0 wasn't so common then) then.

    Anyway, to answer your question, there's no special built in function for that.

    But there are a gazillion modules on CPAN dealing with dates and times.

      Hours will be like 24 hours.
      yes for 24 hours i want that to be '00' only and the day should be next day.
      currently we don't have right to install any modules from cpan. we can use only input modules in perl.
        Well, if you can't install any CPAN modules, you could use a module that comes bundled with perl, namely POSIX. The below example code shows how to create a calendar time for December 12, 1995, at 10:30 am:

        $time_t = POSIX::mktime( 0, 30, 10, 12, 11, 95 ); print "Date = ", POSIX::ctime($time_t);

        Presumably you could create 2 calendar times and subtract one from the other using difftime, which will give you the difference in seconds - format as required for display.

        UPDATE (small example):

        use strict; use warnings; use POSIX qw(mktime difftime ctime); my $previous = '10111623'; my $current = '10111705'; my $time1 = mktime( 0, 0, $4, $3, $2 - 1, $1 + 100 ) if $previous =~ m +/(\d\d)(\d\d)(\d\d)(\d\d)/; my $time2 = mktime( 0, 0, $4, $3, $2 - 1, $1 + 100 ) if $current =~ m/ +(\d\d)(\d\d)(\d\d)(\d\d)/; printf("%s - %s = %d seconds\n", ctime($time2), ctime($time1), difftim +e($time2, $time1));


        Wed Nov 17 05:00:00 2010 - Tue Nov 16 23:00:00 2010 = 21600 seconds
        currently we don't have right to install any modules from cpan. we can use only input modules in perl.
        That's a (silly) political problem not for us to solve. Besides, you can always copy the code from the module and put it in your code (assuming you have the right to install that - if they're consistent, you shouldn't be allowed to install/run your code, it not being part of "perl").
Re: Date and time difference
by sundialsvc4 (Abbot) on Nov 17, 2010 at 15:44 UTC

    It is usually also a very good idea to write your code so that it actually checks the data, to be certain that the specified date/time actually exists.   I have probably encountered “GIGO” (and “pseky, esaily-overlookd litle tpyos”) more often in the context of date-strings than anything else.

    To that end, using the DATE modules previously mentioned is likely to be a smart thing to do, because these modules are coded defensively.   Use a regular expression to pick-apart the date string, then actually check that (say...) the rightmost of these terms was actually extracted, then stuff the list of scalars into the DATE module of your choice.

Re: Date and time difference
by Marshall (Abbot) on Nov 19, 2010 at 01:11 UTC
    You example output is a bit different that what you asked for in text. I assume example output is what you want, generate date strings between previous and current...

    If you can't install a module, this isn't much code to just roll a couple of simple routines that convert your string format into "epoch seconds" and also convert "epoch seconds" back into your string.

    Notes: the $month value is from [0..11] instead of [1..12] to make it easy to use it as an index to look up some text for the month in an array.

    If these are local times instead of UTC times, then you will have to consider what happens if the date span includes the daylight savings time switchover. The local versions, ie timelocal and localtime know about DST. And you can figure out if a time is during the DST period by a flag that is returned if you want some special handling of that case. Start with localtime and go from there. However, the DateTime module would make your life easier if you are indeed working in local time - you don't say... See other postings about installing modules. timegm() does know about leap years so that isn't a problem.

    The Time::Local module will be installed already.

    #!/usr/bin/perl -w use strict; use Time::Local; my $previous = '10111623'; my $current = '10111705'; my $onehour = 60*60; #hour in seconds is 60sec*60min my $cur = date2timegm($previous); my $stop = date2timegm($current); my @result; while ( ($cur+=$onehour) < $stop) { push(@result, timegm2date($cur)); } print join(',',@result),"\n"; #prints: 10111700,10111701,10111702,10111703,10111704 sub timegm2date # returns date string { my $epoch = shift; my ($yr,$mon,$day,$hour) = (gmtime($epoch))[5,4,3,2]; $mon++; $yr+= 1900; $yr = ($yr =~ m/(\d\d)$/)[0]; return (sprintf ("%02d%02d%02d%02d", $yr, $mon, $day, $hour)); } sub date2timegm #returns an epoch time in seconds { my $date = shift; my ($yr,$mon,$day,$hour) = $date =~ m/\d\d/g; --$mon; return (timegm(0,0,$hour,$day,$mon,$yr)); }

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://871978]
Approved by Corion
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (7)
As of 2017-12-18 21:17 GMT
Find Nodes?
    Voting Booth?
    What programming language do you hate the most?

    Results (498 votes). Check out past polls.