How to Check Timezone in Linux
In this short article, we will walk newbies through the various simple ways of checking system timezone in Linux. Time management on a Linux machine especially a production server is always an important aspect of system administration.
There are a number of time management utilities available on Linux such as date and timedatectl commands to get the current timezone of system and synchronize with a remote NTP server to enable an automatic and more accurate system time handling.
Well, let us dive into the different ways of finding out our Linux system timezone.
1. We will start by using the traditional date command to find out present timezone as follows:
Alternatively, type the command below, where %Z format prints the alphabetic timezone and %z prints the numeric timezone:
Note: There are many formats in the date man page that you can make use of, to alter the output of the date command:
2. Next, you can likewise use timedatectl, when you run it without any options, the command displays an overview of the system including the timezone like so:
More so, try to employ a pipeline and grep command to only filter the timezone as below:
3. In addition, users of Debian and its derivatives can display the content of the file /etc/timezone using cat utility to check your timezone:
Important: For REHL/CentOS 7 and Fedora 25-22 users, the file /etc/localtime is a symbolic link to the timezone file under the directory /usr/share/zoneinfo/.
However, you can use date or timedatectl command to display the current time and timezone as well.
To change the timezone, create the symbolic link /etc/localtime to the appropriate timezone under /usr/share/zoneinfo/:
The flag -s enables creation of a symbolic link, otherwise a hard link is created by default and -f removes an existing destination file, which in this case is /etc/localtime.
For example, to change the timezone to Africa/Nairobi, issue the command below:
That’s all! Do not forget to share you thoughts about the article by means of the feedback form below. Importantly, you should look through this time management guide for Linux to get more insight into handling time on your system, it has simple and easy-to-follow examples.
Lastly, always remember to stay tunned to Tecmint for the latest and interesting Linux stuff.
Sorry, you have been blocked
This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.
What can I do to resolve this?
You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.
Cloudflare Ray ID: 7d99e2358a7777bc • Your IP: Click to reveal 88.135.219.175 • Performance & security by Cloudflare
Как изменить часовой пояс Linux
Мы очень часто пользуемся временем в Linux, начиная от простой задачи узнать сколько сейчас времени, до более сложной — посмотреть логи или узнать когда произошло то или иное событие в системе. Все завязано на времени, поэтому очень важно, чтобы часы шли правильно.
Наша планета разделена на часовые пояса, это было сделано с одной простой целью, чтобы время в любой точке планеты соответствовало солнечному времени. Время между этими зонами отличается на час и всего таких поясов — 24, за эталон взято время по нулевому, Гринвичскому меридиану.
Поэтому в определенный момент время в разных участках планеты будет отличаться на час. В этой небольшой статье мы рассмотрим как изменить часовой пояс Linux, чтобы операционная система правильно работала со временем и могла правильно его синхронизировать через интернет.
Как работает время в Linux?
Операционная система Linux хранит и обрабатывает системное время в специальном Unix формате — количество секунд прошедших с полуночи первого января 1970 года. Эта дата считается началом эпохи Unix. И используется не ваше локальное время, а время по гринвичскому меридиану.
Для преобразования времени по Гринвичу в региональное время используется часовой пояс. Это преобразование выполняется для каждого пользователя. Это необходимо, чтобы каждый пользователь мог настроить для себя правильное по его временной зоне время. Такое поведение просто необходимо на серверах, когда на одной машине могут работать люди из разных частей мира.
По умолчанию в системе может быть установлен неправильный часовой пояс, это приведет к путанице в логах событий, да и другим трудностям. Но все это легко исправить. Дальше мы рассмотрим несколько способов изменить часовой пояс Linux.
Настройка часового пояса в linux
1. Ссылка /etc/localtime
Наиболее популярный и поддерживаемый в большинстве дистрибутивов способ установки часового пояса для всех пользователей — с помощью символической ссылки /etc/localtime на файл нужного часового пояса. Список доступных часовых поясов можно посмотреть командой:
Сначала создайте резервную копию текущего часового пояса:
cp /etc/localtime /etc/localtime.bak
Для создания символической ссылки используйте команду ln -sf. Файл зоны нужно выбрать из доступных в системе. Например, мой часовой пояс — Украина, Киев, для установки будет использоваться следующая команда:
ln -sf /usr/share/zoneinfo/Europe/Kiev /etc/localtime
Теперь можете проверить текущее системное время с помощью утилиты date:
Если у вас установлена утилита rdate можно синхронизировать время с сетью:
sudo rdate -s time-a.nist.gov
Осталось только синхронизировать ваши аппаратные часы с новыми настройками, для этого выполните команду:
Если нужно изменить часовой пояс только для определенной программы или скрипта, просто измените для нее переменную окружения TZ, например:
Эта настройка сохраняется только для текущего сеанса командной оболочки. Чтобы сменить часовой пояс linux для определенного пользователя тоже нужно использовать переменную среды TZ. Только ее нужно добавить в файл
/.environment. Этот файл читается по умолчанию при входе в систему, а значит переменная будет доступна всем программам:
Готово, теперь вы знаете как выполняется настройка часового пояса linux для определенного пользователя.
2. Настройка с помощью tzdata
Если вы не хотите использовать описанный выше способ, можно воспользоваться специальными утилитами. Вот только в разных дистрибутивах используются свои утилиты. Рассмотрим варианты для самых популярных дистрибутивов.
В Red Hat Linux:
В CentOS и Fedora:
В Slackware или FreeBSD:
В большинстве случаев вы увидите подобное диалоговое окно:
Здесь просто нужно выбрать нужный часовой пояс и нажать кнопку Enter. После этого для окончательного применения настроек нужно будет перезагрузить систему.
3. Настройка с помощью systemd
В systemd есть своя утилита для настройки даты и часового пояса. Чтобы узнать текущее состояние выполните:
Для просмотра всех доступных временных зон выполните такую команду:
А для установки нужного часового пояса используйте команду set-timezone, например, тот же Europe/Kiev:
sudo timedatectl set-timezone Europe/Kiev
4. Настройка часового пояса в GUI
В дистрибутиве Ubuntu и других, использующих Gnome, настройка часового пояса Linux может быть выполнена прямо в параметрах системы. Для этого выберите пункт Сведения о системе, затем Дата и время, выберите свое местоположение на карте, или наберите название для поиска в поле ввода:
В KDE аналогично можно установить часовой пояс в настройках системы. Запустите утилиту настроек, откройте пункт Локализация, перейдите в раздел Дата и время, а затем откройте вкладку Часовой пояс:
Остается выбрать часовой пояс в списке и нажать кнопку Применить. Здесь уже изменения должны проявиться моментально.
Выводы
Теперь вы знаете как выполняется установка часового пояса в linux и сможете настроить не только свой домашний компьютер но и сервер с множеством пользователей, которым нужен отдельный часовой пояс для правильного местного времени. Если у вас остались вопросы, спрашивайте в комментариях!
На завершение видео, в котором подробно рассказано, что такое часовые пояса и зачем они нужны:
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
How to check which timezone in Linux?
Is there a way to check which time zone I’m currently in on Linux?
16 Answers 16
Usually, the TZ environment variable will tell you something useful. However, it is best to use functions such as mktime() and localtime() to convert between time_t and a local timezone representation. That is, don’t try to do the conversion yourself.
If you mean from the console, just type:
If you want the numeric timezone:
date +’%:z %Z’
I wanted to find the timezone in «US/Eastern» or «Europe/London» form instead. You can find this in:
- /etc/timezone (present on Ubuntu and Red Hat? but not e.g. Amazon Linux)
- (on Red Hat style systems) as ZONE=»US/Eastern» in /etc/sysconfig/clock
or you can try and match /etc/localtime to one of the files under /usr/share/zoneinfo; annoyingly this doesn’t seem to be a symlink, but you can e.g.
cd /usr/share/zoneinfo
find * -type f -exec sh -c «diff -q /etc/localtime ‘<>‘ > /dev/null && echo <>» \;
to find matching files — there’s probably better ways to do that, but that works. There will be multiple matches.
For ubuntu try this :
Sometimes you may be looking for the canonical timezone rather than the short form as produced by date %Z e.g. US/Eastern . On systems with timedatectl e.g. Fedora, timedatectl outputs lots of useful information, including the current zone:
Unfortunately, timedatectl takes set-timezone as a command, but has no corresponding get-timezone . Parse it as follows:
For systemd >= 241, see @BurninateSE’s answer (TLDR: timedatectl show —va -p Timezone ).
For the time zone, you can use geolocation:
All of the following solutions will give you an IANA compatible Olson timezone ID (e.g. America/Los_Angeles ). However, some may return extra whitespace at the beginning and/or end — trim if required.
Using the environment
The environment variable TZ (if set) specifies the timezone. Checking this first is essential.
I can personally confirm that this works on ALL of my modern Linux hosts.
Using Systemd version >= 241
This is the preferred method for all those who believe Systemd shall rule the world.
If you get an error similar to timedatectl: invalid option — ‘p’ that means your Systemd isn’t ready to rule the world. Instead.
Using Systemd and sed
Improvement upon Raman’s answer, but without the useless use of grep. This solution is optimal on systems utilizing older versions of Systemd.
Using /etc/timezone
This is a simple readable file, but doesn’t seem to be available on as many distros anymore. IIRC, this is something those Debian devs came up with a while ago that fell out of favour.
Using GNU realpath because /etc/localtime is a symlink
This solution is optimal if you know that /etc/localtime is a symlink, which is something that both a lot of older software and guides accomplish and even modern SystemD promises; and you also have GNU realpath available, which should also be available on every GNU OS distro.
D’oh! /etc/localtime isn’t a symlink; using find , sed , md5sum
If you find yourself with a non-symlink /etc/localtime (the command shown above will either error or provide a path that starts with ../ ), you can try to locate its md5 match in your local timezone database. This may return multiple matches as there are quite a few aliases in the Olson database.
If you’d only like a single timezone ID returned (whichever one is returned first by the system’s readdir()), you can use sed’s q command to quit after the first match. This is much more performant than starting up head for instance. However, this causes find to break the pipe with md5sum early, causing an error to print to fd 2. You may ignore this error by piping it to /dev/null as the following complete command demonstrates:
Using curl and geolocation
If for some reason you don’t want or don’t trust the host’s configuration (or just hate their guts) but you’re certain that it can connect to the wider world web, there are several gratis online services that will geolocate you (whilst they last). Below are some examples:
First two services shamelessly stolen from Steven Penny’s answer. Additionally I implore the SE community to please keep this list up to date with working links thanks!
Finally, I beg of you to please don’t use this method to bind your users and steal their agency — only use this method if they ask you to do so!
Also note that while these services are gratis, please consider visiting their respective web sites to learn about and accept their terms and conditions before using.