Perl convert microseconds since epoch to localtime - perl

In perl, given microseconds since epoch how do I convert to localtime in a format like
my $time = sprintf "%02ld,%02ld,%02ld.%06ld", $hour, $min, $sec, $usec;
Eg: "Input = 1555329743301750 (microseconds since epoch) Output = 070223.301750"

The core Time::Piece can do the conversion, but it doesn't handle subseconds so you'd need to handle those yourself.
use strict;
use warnings;
use Time::Piece;
my $input = '1555329743301750';
my ($sec, $usec) = $input =~ m/^([0-9]*)([0-9]{6})$/;
my $time = localtime($sec);
print $time->strftime('%H%M%S') . ".$usec\n";
Time::Moment provides a nicer option for dealing with subseconds, but needs some help to find the UTC offset for the arbitrary time in system local time, we can use Time::Moment::Role::TimeZone.
use strict;
use warnings;
use Time::Moment;
use Role::Tiny ();
my $input = '1555329743301750';
my $sec = $input / 1000000;
my $class = Role::Tiny->create_class_with_roles('Time::Moment', 'Time::Moment::Role::TimeZone');
my $time = $class->from_epoch($sec, precision => 6)->with_system_offset_same_instant;
print $time->strftime('%H%M%S%6f'), "\n";
Finally, DateTime is a bit heavier but can handle everything naturally, at least to microsecond precision.
use strict;
use warnings;
use DateTime;
my $input = '1555329743301750';
my $sec = $input / 1000000;
my $time = DateTime->from_epoch(epoch => $sec, time_zone => 'local');
print $time->strftime('%H%M%S.%6N'), "\n";
(To avoid possible floating point issues, you could replace my $sec = $input / 1000000 with substr(my $sec = $input, -6, 0, '.') so it's purely a string operation until it goes to the module, if you are sure it will be in that string form - but it's unlikely to be an issue at this scale.)

Related

Get previous hour of UTC/GMT time using Perl

I have a script which will print Start & End time of previous hour of UTC/GMT.
#!/usr/local/bin/perl
use strict;
use warnings;
use POSIX qw(strftime);
my ($tmp_date, $tmp_hour, $Start, $End);
my $date = strftime '%Y-%m-%d', gmtime();
print "Date:$date\n";
my $hour = strftime '%H', gmtime();
print "Hour:$hour\n";
if ($hour == "00"){
$tmp_date = $date-1;
$tmp_hour = "23";
} else {
$tmp_hour = $hour-1;
$tmp_date = $date;
}
$a = length($tmp_hour);
if ($a == 1 ){
$tmp_hour="0".$tmp_hour;
}
$Start = $tmp_date.".".$tmp_hour."00";
$End = $tmp_date.".".$hour."05";
if ($End =~ /0005/){
$tmp_date = `TZ=GMT-12 date +%Y%m%d`;
$End =$tmp_date.".".$hour."05";
}
print "Start:$Start, End:$End\n";
For example, lets say now UTC time is: Wed Jun 10 10:18:57 UTC 2020
This should print Start & End time as 2020-06-10.0900 2020-06-10.1005 respectively.
This script is working as expected. But when Daylight savings happens will there be any impact on fetching Start & End time?
I want experts suggestions how can I avoid unnecessary if statements and achieve it by the use of Perl module itself.
PS: Perl version: v5.10.1. Please suggest Perl modules which comes with standard Perl installation (Ex: POSIX, Time::Local etc.) for solution of above problem.
As you're using gmtime(), any DST changes will have no effect at all.
I'm not sure why your end time ends with '05', I would have thought that the end of the hour comes at '00'.
Here's how I'd write it with Time::Piece and Time::Seconds.
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use Time::Piece;
use Time::Seconds;
my $end = gmtime->truncate(to => 'hour');
my $start = $end - ONE_HOUR;
my $format = '%Y-%m-%d %H:%M:%S';
say 'Start: ', $start->strftime($format);
say 'End: ', $end->strftime($format);
If you really want the end time to be five past the hour, then add this line after the ONE_HOUR line:
$end += (5 * ONE_MINUTE);
You can, of course, use any of the standard strftime() sequences to change the format of the output.

Perl subtract two dates

I am fairly new in Perl.
I am trying to subtract two dates in this format
15.07.16 23:13:34
15.07.16 20:04:24
I know that I have to convert this string in a date object. My problem is I am restricted to the basic perl without installing extra packages. Is there a way to do it?
My Version is v5.8.4 and the output should be 03:09:10.
You say that you're using Perl 5.8.4. You really need to get that updated and get the ability to install CPAN modules.
But, here's a way to do what you want using only core Perl functionality that was available in 5.8.4.
#!/usr/bin/perl
use strict;
use warnings;
use Time::Local;
my $date1 = '15.07.16 23:13:34';
my $date2 = '15.07.16 20:04:24';
my $diff = date2sec($date1) - date2sec($date2);
print secs2duration($diff);
sub date2sec {
my ($date) = #_;
my ($day, $mon, $yr, $hr, $min, $sec) = split(/[. :]/, $date);
# I've assumed that your timestamps are in your local timezone,
# so I've used timelocal() here. If your timestamps are actually
# UTC, you should use timegm() instead.
return timelocal($sec, $min, $hr, $day, $mon-1, 2000 + $yr);
}
sub secs2duration {
my ($secs) = #_;
my $hours = int($secs / (60*60));
$secs %= (60*60);
my $mins = int($secs / 60);
$secs %= 60;
return sprintf '%02d:%02d:%02d', $hours, $mins, $secs;
}

Date::Manip::Delta - the number of seconds [duplicate]

The code below only expresses the difference in months and days like so:
0:2:0:5:0:0:0
So it works, but I want to know the total number of days given that $ADDate can vary quite a bit. Hopefully this is simple, and I just completely missed how to do it.
#!/usr/bin/perl
use Date::Manip 6.42;
my $ADDate = "20131211000820.0Z";
my $var;
my #val;
my $diff;
calc_period($ADDate = "20131211000820.0Z");
sub calc_period
{
$ADDate =~ s/^([\d][\d][\d][\d])([\d][\d])([\d][\d])/$1-$2-$3/gs;
$ADDate =~ s/.........$//gs;
$today = ParseDate("today");
$beginning = ParseDate($ADDate);
$end = ParseDate($today);
$delta = DateCalc($beginning,$end,\$err,1);
#$delta =~ s/([\d+][:][\d+]):.*$/$1/gs;
print "$delta\n";
print "$ADDate\n";
}
I'm not familiar with Date::Manip, but I think another way to do this is to use Time::Piece to parse your string and do whatever you like with that since taking the difference of two Time::Piece object returns a Time::Seconds object.
The following example will show the difference of the current time and the hardcoded time and show it in days.
#!/usr/bin/perl
use strict;
use warnings;
use Time::Piece;
use Time::Seconds;
my $d = "20131211000820.0Z";
my $t = Time::Piece->strptime($d, "%Y%m%d%H%M%S.0Z");
my $now = Time::Piece->localtime();
my $diff = Time::Seconds->new($now - $t);
print $diff->days, "\n";
NigoroJr has already given you an answer. However, just as an FYI, the following is how I would clean up the code you originally provided:
#!/usr/bin/perl
use Date::Manip 6.42;
use strict;
use warnings;
calc_period("20131211000820.0Z");
sub calc_period {
my $date = shift;
$date =~ s/^(\d{4})(\d{2})(\d{2}).*/$1-$2-$3/;
my $beginning = ParseDate($date);
my $end = ParseDate("today");
my $delta = DateCalc($beginning, $end, \my $err, 1);
#$delta =~ s/([\d+][:][\d+]):.*$/$1/gs;
print "$delta\n";
print "$date\n";
}
Biggest differences being the proper use of a function and scoped variables, and a simplification of your regex.
I was unable to find a clean way to get Date::Manip to output a strict delta in days though, so the other module is the way to go.

Perl - How to convert a date?

How to convert date format YYYY-MM-DDTHH:MM:SSZ to YYYY-MM-DD HH:MM + 8 hours?
For example:
Input: 2011-07-07T18:05:45Z
Output: 2011-07-08 02:05
Let's start with Rahul's snippet, and add in the date math and output formatting...
use DateTime;
use DateTime::Format::ISO8601;
use DateTime::Format::Strptime;
my $string = '2011-07-07T18:05:45Z';
my $dt = DateTime::Format::ISO8601->parse_datetime( $string );
die "Impossible time" unless $dt;
my $formatter = new DateTime::Format::Strptime(pattern => '%Y-%m-%d %T');
$dt->add( hours => 8 )->set_formatter($formatter);
print "$dt\n";
I've added the use of DateTime::Format::Strptime, in order to specify the desired output format.
Then I've added three more lines:
First I create a formatter, and feed it the output pattern I desire.
Next I add eight hours to the original date, and I assign the output
formatter by chaining the set_formatter() call to the add() call.
Then I print it.
Are you using the DateTime modules?
Specifically, here's a link to DateTime::Format::ISO8601 that reads/writes ISO 8601 format you mentioned as your input.
If you don't have DateTime, you surely have Time::Piece:
use strict;
use warnings;
use Time::Piece;
use Time::Seconds qw(ONE_HOUR);
my $str = '2011-07-07T18:05:45Z';
my $t = Time::Piece->strptime($str, "%Y-%m-%dT%TZ");
$t += 8 * ONE_HOUR;
print $t->strftime("%Y-%m-%d %H:%M"),"\n";
Taken From
How can I validate a "yyyy-MM-dd'T'HH:mm:ssZ" date/timestamp in UTC with Perl?
use DateTime;
use DateTime::Format::ISO8601;
my $string = '2010-02-28T15:21:33Z';
my $dt = DateTime::Format::ISO8601->parse_datetime( $string ); die "Impossible time" unless $dt;
It doesn't work, result is 2010-02-28T15:21:33
Then, do it the hard way...
use Time::Local
use warnings;
use strict;
$time = '2010-02-28T15:21:33Z';
my ($year, month, day) = split (/-/, $time)
$year -= 1900; #Year is an offset of 1900
$month -= 1; #Months are 0 - 11
#Now split the time off of the day (DDTHH:MM:SS)
$day = substr($day, 0, 2);
time = substr($day, 3)
#Now split the time
(my $hour, $minute, $second) = split(/:/, $time);
$second =~ s/Z$//; #Remove Z
my $time_converted = timelocal($second, $minute, $hour, $day, $month, $year);
#Now you have the time, Add eight hours
my $hours_in_seconds = 8 * 60 * 60;
$time_converted += $hours_in_seconds;
# Almost done: Convert time back into the correct array:
($second, $minute, $hour, $day, $month, $year) = localtime($time_converted);
$year += 1900;
$month += 1;
# Now, reformat:
my $formatted_time = sprint (%04d-%02d-%02d %02d:%02d),
$year, $month, $day, $hour, $minute;

How do I convert local time to a Unix timestamp in Perl?

For example: from date: 10/02/2010
How do I convert an equal timestamp for 10/02/2010 00:00:00 in Perl?
I can't use local time or time .. is there another way to achieve this?
You can use the Time::Local core module:
use Time::Local 'timelocal';
my ($d, $m, $y) = split '/', '10/02/2010';
my $time = timelocal(0, 0, 0, $d, $m-1, $y);
Note that the month argument for timelocal() is in the range 0..11.
Without localtime():
use Time::Local;
$time = timelocal($sec, $min, $hour, $mday, $mon, $year);
(See perldoc.)
A standard way would be something like:
use POSIX;
use strict;
use warnings;
my $sec = 0;
my $min = 0;
my $hour = 0;
my $day = 10;
my $mon = 2 - 1;
my $year = 2010 - 1900;
my $wday = 0;
my $yday = 0;
my $unixtime = mktime ($sec, $min, $hour, $day, $mon, $year, $wday, $yday);
print "$unixtime\n";
my $readable_time = localtime($unixtime);
print "$readable_time\n"
(From Converting Unix time and readable time with Perl)
You could use Date::Parse:
use Date::Parse;
print str2time('10/02/2010 00:00:00');
On my machine this prints 1285970400, which corresponds to October 2nd, 2010 (I live in +1 GMT with +1 Wintertime.)
I think you want the built-in module Time::Local.
The DateTime module should be helpful here. In particular, I believe the DateTime::Format::Natural module can parse a user-supplied date string. From there, you have a DateTime object and can print it out or transform it as you like.
Depending on where your initial date is coming from you might be able to parse it using
Date::Manip
and calling
ParseDate("10/02/2010")
You can then take that output and convert it into whatever format you wish.