Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine the current timezone a machine is set to with Perl?

Tags:

perl

I had assumed it would be as simple as $ENV{TZ}, but the TZ environment variable is not set, and yet the date command still knows I am in EDT, so there must be some other way of determining timezone (other than saying chomp(my $tz = qx/date +%Z/);).

like image 524
Chas. Owens Avatar asked Jun 13 '09 03:06

Chas. Owens


People also ask

How do I get the current time in Perl?

localtime() function in Perl returns the current date and time of the system, if called without passing any argument.

How do I change the timezone in Perl?

Use POSIX::tzset.

How do I format a date in Perl?

The Perl POSIX strftime() function is used to format date and time with the specifiers preceded with (%) sign. There are two types of specifiers, one is for local time and other is for gmt time zone.

How do I find the timezone of a python server?

You can get the current time in a particular timezone by using the datetime module with another module called pytz . You can then check for all available timezones with the snippet below: from datetime import datetime import pytz zones = pytz. all_timezones print(zones) # Output: all timezones of the world.


3 Answers

If you want something more portable than POSIX (but probably much slower) you can use DateTime::TimeZone for this:

use DateTime::TimeZone;

print DateTime::TimeZone->new( name => 'local' )->name();
like image 151
Dave Rolsky Avatar answered Oct 29 '22 00:10

Dave Rolsky


use POSIX;
localtime();
my ($std, $dst) = POSIX::tzname();

tzname() gives you access to the POSIX global tzname - but you need to have called localtime() for it to be set in the first place.

like image 20
Beano Avatar answered Oct 29 '22 01:10

Beano


If you just need something like +05:30 (UTC+5.5/India time), you may use the following code.

my @lt = localtime();
my @gt = gmtime();

my $hour_diff = $lt[2] - $gt[2];
my $min_diff  = $lt[1] - $gt[1];

my $total_diff = $hour_diff * 60 + $min_diff;
my $hour = int($total_diff / 60);
my $min = abs($total_diff - $hour * 60);

print sprintf("%+03d:%02d", $hour, $min);

This answer is inspired by Pavel's answer above.

like image 28
sancho21 Avatar answered Oct 29 '22 02:10

sancho21