Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Perl date conversion

by gio001 (Acolyte)
on Mar 23, 2011 at 17:19 UTC ( #895052=perlquestion: print w/ replies, xml ) Need Help??
gio001 has asked for the wisdom of the Perl Monks concerning the following question:

Hello everyone, I am using the following Perl one liner in a ksh script to process a file of dates and change them to a different format and attach a counter of 1 to each date processed. I must have something wrong, when I have entries like:
1300483666
which is Fri Mar 18 17:27:46 2011 for which I would expect an output of the form:
2011 03 18 05 21 1
this code returns:
2011 03 18 05 17 1
This is the code I use :
perl -lne '($j1,$j2,$hour,$mday,$mon,$year,$wday) = gmtime($_);$year = + $year + 1900;$mon++;printf("%4s %.2d %.2d %.2d %.2d %6s\n",$year,$mo +n,$mday,$wday,$hour,1);' < inputFile >outputFile
I really hope someone can help and explain my error. Thanks!

Comment on Perl date conversion
Select or Download Code
Re: Perl date conversion
by toolic (Chancellor) on Mar 23, 2011 at 17:24 UTC
    I can not reproduce your results. Are you sure your input file is what you think it is?
    echo 1300483666 | perl -lne '($j1,$j2,$hour,$mday,$mon,$year,$wday) = +gmtime($_);$year = $year + 1900;$mon++;printf("%4s %.2d %.2d %.2d %.2 +d %6s\n",$year,$mon,$mday,$wday,$hour,1);' 2011 03 18 05 21 1
      My message is incorrect, I want to have this output from an input of 1300483666 : 2011 03 18 05 17      1 and instead the code returns: 2011 03 18 05 21      1 Sorry for the mistake. Can you help? I suppose I can make the gmtime($_) be like gmtime($_-14400) but I thought there might be a cleaner way to resolve the date in input to my local time (EST or EDT whatever it happens to be). Can I do without the gmtime all together? Hope you can help. Thanks
        I replaced gmtime with localtime and it seems to work properly. Thanks Any advice anyway?
Re: Perl date conversion
by Fletch (Chancellor) on Mar 23, 2011 at 18:22 UTC

    Use strftime from POSIX (granted it only prints the day-of-week as only a single digit so it's not 100% equivalent if (e.g.) you need fixed columns)

    perl -MPOSIX=strftime -lne 'print strftime("%Y %m %d %w %H\t1",localti +me($_))'

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://895052]
Approved by toolic
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (3)
As of 2014-07-26 11:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (175 votes), past polls