Как поменять время в linux
Перейти к содержимому

Как поменять время в linux

  • автор:

Learning Ubuntu: Set Timezone (3 Easy Methods)

Learning Ubuntu: Set Timezone (3 Easy Methods)

Using the correct date and time on your Ubuntu system is essential for tasks and processes such as data logging, cron jobs, and the overall management of a Linux-based VPS setup.

Most applications also use the timezone to manage their data accordingly. When it comes to Ubuntu, the system’s timezone is set during the initial setup, but users can still change it.

This article will discuss how to set a timezone in Ubuntu using three easy methods. Refer to our other guide if you’re looking to change timezone on CentOS.

How to Set the Timezone on Ubuntu

In this section, we will show step-by-step how to set the timezone on Ubuntu so you can better manage your Linux VPS. Make sure to log in as a root user to perform the following actions.

Using the Graphical User Interface (GUI)

The most convenient way to change the timezone on an Ubuntu system is via the graphical user interface (GUI). Since it is accessible from the desktop, users don’t have to run any commands.

Here’s how to change the timezone using the GUI – the instructions are applicable for Ubuntu 18.04, Ubuntu 20.04, and Ubuntu 22.04:

  1. Click on the System menu on the top-right corner of the screen.
  2. Select Settings and go to the Date & Time tab.

The Date and Time menu of Ubuntu desktop

  1. Turn the Automatic Time Zone option to OFF. If it is ON and the system is connected to the internet, it will automatically set the timezone according to the user’s location.

The Automatic Date and Time option turned off

  1. Click on Time Zone.

The date and time menu of Ubuntu with the time zone option highlighted

  1. A new window will open. Select the new timezone by clicking on the map directly or using the search bar.

Ubuntu

  1. Once done, click on the x button to close the window.

Check the Time Zone box inside the Date & Time tab to verify if the new timezone and current date were successfully updated.

Date Time and Time Zone in Ubuntu desktop changed

Using timedatectl (via the Command Line)

There are two ways to set up a server’s timezone in the command line – using tzselect or timedatectl. However, the first command only works to change the timezone temporarily.

If you opt for tzselect, the timezone will revert to the one set in the /etc/timezone file after a reboot. You can still use this command as an alternative way to list the timezone options on the system.

To do so, open Terminal or your command-line interface (CLI) and run the tzselect command. Then, specify the desired timezone and press Enter.

List timezones option on Ubuntu terminal

One of the best methods to permanently change the timezone on Ubuntu is using the timedatectl command. It is a Linux utility that allows users to review and change the configuration of the system clock.

In addition, the timedatectl command enables users to modify the system’s current time and date, set a timezone, and automatically synchronize the clock via a remote server. We recommend it if your machine is running Ubuntu 18.04, Ubuntu 20.04, or Ubuntu 22.04.

Here’s how to change the timezone using this method:

  1. Open your CLI. Check the current system’s timezone by running the timedatectl command.
  1. The output below shows that the local time is set to Coordinated Universal Time (UTC).

Output showing that the system

  1. Find out the full name of the timezone. Usually, the naming convention uses the Region/City format. Insert the command below to see the timezone list:

List of timezones on Ubuntu terminal

  1. Alternatively, combine the timedatectl command with the grep command to filter the search using the name of a city.
  1. Press CTRL + C to exit.
  2. Once you have decided which timezone to select, run the following command to make the change. Note that it will not produce any output:
  1. Insert the command below and press Enter to verify the update:

The time zone and system clock synchronized values show that the new local time was updated successfully.

Using the tzdata Command (Older Ubuntu Versions)

Users of Ubuntu versions such as 16.04 or lower can set their timezones by reconfiguring the timezone and daylight saving time data or tzdata. It contains files documenting both current and historical transitions of time zones around the world.

Follow these steps to change the timezone using the tzdata command:

  1. Type in the following command to reconfigure tzdata and press Enter:
  1. The package configuration window will open. Choose your geographic area and press Enter.

The tzdata interface with geographic areas shown

  1. Select OK, and press Enter.
  2. Next, select the city or region corresponding to the timezone.

List of available timezones using tzdata

  1. Select OK and hit Enter.
  2. An output will automatically appear to ensure your current timezone was set correctly.

Current default time zone updated to Europe/Paris

You can also find your Linux system’s timezone information in the /etc/timezone directory.

Conclusion

Using the correct timezone is important for a system’s processes, as it defines when those tasks will be deployed and done. On Ubuntu, users usually set up the system clock during the initial installation.

However, the current timezone is adjustable using three easy methods – the graphical user interface (GUI), the timedatectl command, or the tzdata command.

If you use Ubuntu 18.04, Ubuntu 20.04, or Ubuntu 22.04, we recommend the GUI method or the timedatectl command. For Ubuntu 16.04 and lower, we recommend reconfiguring tzdata.

We hope this article has helped you set up the timezone on your Ubuntu system. If you have any questions or suggestions, leave them in the comments section below.

Learn more about Ubuntu

Edward is a content editor with years of experience in IT writing, marketing, and Linux system administration. His goal is to encourage readers to establish an impactful online presence. He also really loves dogs, guitars, and everything related to space.

Установка времени Linux

Время от времени часы на компьютере могут сбиваться по различным причинам, время может быть установлено изначально неправильно или неправильно выбран часовой пояс. Хотя в системе по умолчанию настроена синхронизация времени с интернетом и я уже давно забыл что значит постоянно перенастраивать часы, если они отстают, такая необходимость может появиться.

В этой статье мы рассмотрим как выполняется установка времени Linux различными способами, через терминал, графический интерфейс и так далее. Но сначала нам нужно понять как работает время.

Как работает время на компьютере?

Статья ориентирована на новичков, в первую очередь на них, потому что профессионалы уже и так знают как это сделать. Поэтому сначала рассмотрим как работает время в Linux. Когда компьютер работает часы идут, это ясно, но когда вы его отключаете, а затем включаете снова часы показывают не то время, на котором остановились, а правильное время. Это происходит потому, что часы на материнской плате идут постоянно. Таймер питается от той же батарейки, что и энергозависимая память BIOS.

Операционная система передает значение таймера в память BIOS при выключении и берет его оттуда при включении. Отсюда берутся проблемы со временем при двойной загрузке Windows и Linux, но эта тема раскрыта в другой статье — сбивается время в Ubuntu и Windows. Другая проблема почему может сбиваться время — это неверно установленный часовой пояс. Если вы установили часовой пояс linux неверно, то часы будут постоянно синхронизироваться через интернет и идти неверно.

Когда все проблемы с временем будут устранены, можно перейти установить нужное время и быть уверенным что оно не будет сбиваться. Дальше рассмотрим как это сделать.

Установка времени Linux

Вы можете видеть текущее время прямо на вашем рабочем столе, в KDE часы добавлены на панель, да и в Gnome, они размещены по центру панели по умолчанию:

Если навести курсор на время, вы увидите более подробную информацию, область уведомлений и календарь.

Но настроить время здесь уже не получится. Для этого нужно открывать настройки системы. Мы будем рассматривать настройки для Gnome. Откройте меню Dash и наберите в строке поиска «Параметры»:

Дальше откройте «Дата и время»:

Как видите, здесь уже установлено значение по умолчанию «Автоматическое определение даты и времени», а внизу есть пункт, который отвечает за часовой пояс.

Вы можете просто поменять часовой пояс чтобы время синхронизировалось правильно, если что-то не так. Также можно задать время вручную. Для этого сначала отключите автоматическую синхронизацию, а затем выберите дату и время:

Никаких кнопок нажимать не нужно, закройте окно выбора и новое время будет применено. Вы всегда можете вернуть настройки до значения по умолчанию.

Установка времени через терминал

Кроме графического интерфейса, у вас есть возможность делать все необходимые действия через терминал. Для этого есть утилита date. Сначала смотрим текущее время:

У утилиты есть множество опций отображения и настроек, но мы не будем их рассматривать. Есть еще одна команда, которая позволяет посмотреть системное время linux:

Чтобы установить время можно использовать ту же команду date. Для этого ей нужно передать строку со временем и датой, например:

В качестве строки можно брать ту, которую возвращает команда date без параметров, только она должна быть на английском, поэтому сразу смотрим:

sudo date —set «Wed Sep 6 20:43:36 EEST 2017»

Если у вас включена коррекция даты через интернет, то ее нужно отключить перед этим, потому что вы даже заметить изменений не успеете, как сервер времени linux установит правильное время. Можно сократить эту строку:

sudo date —set «Sep 6 20:43:36 2017»

Это даст тот же результат. Еще один вариант — указать формат данных, которые вы собираетесь передавать с помощью модификаторов, например, изменить время linux:

sudo date +%T -s «20:43:36»

Здесь формат очень прост — часы:минуты:секунды. Можно давать время в 12 часовом формате, для этого добавьте модификатор %p:

date +%T%p -s «8:43:36PM»

Вы изменяете текущее время, но аппаратное системное время linux не изменяется, чтобы сохранить изменения используйте команду:

Еще один новый инструмент от systemd для управления временем — timedatectl. С помощью него можно выполнить те же операции, сначала смотрим доступную информацию о времени:

Текущее системное время отображается в строке Local Time. Чтобы изменить дату, используйте опцию -set-time. Синтаксис передаваемого ей параметра такой: ГГГГ-ММ-ДД ЧЧ:ММ:СС. Думаю тут понятно и без комментариев. Например:

sudo timedatectl —set-time «2017-09-06 20:43:36»

Можно задать только время, тогда нужно использовать синтаксис времени ЧЧ:ММ:СС, например:

sudo timedatectl —set-time «20:43:36»

Еще раз говорю, что если включена синхронизация по сети, то вы не сможете изменить время. Но с помощью timedatectl ее можно отключить:

sudo timedatectl set-ntp no

Или включить обратно:

sudo timedatectl set-ntp yes

C помощью этой же команды можно не только установить время linux, но и настроить часовой пояс, для этого используйте опцию set-timezone:

sudo timedatectl set-timezone ‘Europe\Kyiv’

Вы можете посмотреть список доступных часовых поясов командой:

Видео о настройке времени с помощью timedatectl:

Выводы

Вот и все. Теперь вы знаете как выполняется установка времени linux. Как видите, это очень просто, вы можете использовать различные способы, в зависимости от того, что вам будет удобнее. Если у вас остались вопросы, спрашивайте в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Как изменить дату и время в консоли linux

Не каждый день возникает необходимость изменять время на компьютере. Как правило оно синхронизируется с NTP сервером времени через интернет. Но время может не сбиваться даже если отсутствует подключение к интернету. Это происходит потому, что установленное время в операционной системе при выключении компьютера записывается в BIOS или UEFI (программное обеспечение материнской платы) и при загрузке компьютера возвращается обратно в операционную систему. BIOS и UEFI хранят многие системные настройки необходимые для запуска компьютера, в том числе ведут постоянный отсчет установленной даты и времени пока компьютер выключен.

По многим причинам время может сбиваться и в таких случая может потребоваться его корректировка. Посмотреть или изменить дату и время в консоли Linux можно с помощью команды date.

Чтобы посмотреть текущую дату и время linux нужно выполнить команду date без аргументов.

Для изменения текущей даты и времени команда date выполняется с аргументом формата MMDDhhmmYYYY.ss, где:

  • MM — месяц;
  • DD — день;
  • hh — часы;
  • mm — минуты;
  • YY — год;
  • ss — секунды.

Изменим только время, установив 12 часов 30 минут, а дату оставим прежней.

Изменение даты и времени необходимо выполнять в привилегированном режиме, поэтому необходимо использовать sudo

Командой date с таким аргументом довольно неудобно пользоваться — все символы сбиты в кучу, порядок записи значений даты и времени трудно запомнить.

Существует более удобный способ изменить время и дату в linux, для это необходимо использовать date совместно с аргументом —set

При таком формате записи отпадает необходимость разъяснять где находится дата (год-месяц-день) и время (часы:минуты:секунды).

Ubuntu Time Management

This page gives useful information about the way that Ubuntu manages time by changing the timezone, setting up synchronization using Network Time Protocol (NTP), and adjusting servers.

Changing the Time Zone

This section shows you how to accomplish this task using either the Graphical User Interface (GUI) or by using the command line (terminal).

Using the GUI

Using the Command Line (terminal)

Using the Command Line (unattended)

    Find out the long description for the timezone you want to configure.

This can be scripted if required.

Time Synchronization using NTP

This page describes methods for automatically keeping your computer’s time accurate. This is extremely useful for servers, and is also recommended for desktop machines.

Network Time Protocol (NTP) is a UDP/IP protocol for synchronizing time over a network connection. Basically a client requests the current time from a server, and then uses the servers response to set its own clock.

Beyond this simple description, there is a lot of complexity. There are multiple tiers of NTP servers, with the tier one NTP servers connected to atomic clocks (often via GPS), and tier two and three servers spreading the load of actually handling requests across the internet. The client software is a lot more complex than you might think as it has to factor communication delays, and adjust the time in a way that does not affect the other processes that run on the system. Luckily all that complexity is hidden from the user.

Using the GUI

Command Line ntpd

ntpdate is a bit of a blunt instrument as it can only adjust the time once a day in one big correction. The ntp daemon ntpd is far more subtle as it calculates the drift of your system clock and continuously adjusts it in small increments. Using ntpd there are no large corrections that could lead to inconsistent logs for instance. The cost is a little processing power and memory, but for a modern system this is negligible.

To setup ntpd in versions of Ubuntu 7.04 and higher

To set up ntpd pre Ubuntu 7.04:

Changing NTP Time Servers

In both cases above, your system will use Ubuntu’s NTP server at ntp.ubuntu.com by default. This is OK, but you might want to use several servers to increase accuracy and resilience, and you may want to use time servers that are geographically closer to you.

Using the GUI

Command Line ntpdate

ntpdate is no longer installed by default on Ubuntu. The file /etc/cron.daily/ntpdate also does not exist anymore

ntpdate, if installed, will run it once at boot time to set up your time according to Ubuntu’s NTP server. However, a system’s clock is likely to drift considerably between reboots if the time between reboots is long. In that case it makes sense to correct the time occasionally. The easiest way to do this is to get cron to run it every day. With your favorite editor, create (needs sudo) a file /etc/cron.daily/ntpdate containing:

Make sure that you make this new file executable:

ntpdate

You may notice pool.ntp.org in the examples above. This is a really good idea which uses round-robin DNS to return an NTP server from a pool, spreading the load between several different servers. Even better, they have pools for different regions — I am in New Zealand, so I use nz.pool.ntp.org instead of pool.ntp.org. Look at http://www.pool.ntp.org/ for more details.

You can also Google for NTP servers in your region, and add these to your configuration. To test that a server works, just type sudo ntpdate ntp.server.name and see what happens.

Multiple Boot Systems Time Conflicts

Operating systems store and retrieve the time in the hardware clock located on your motherboard so that it can keep track of the time even when the system does not have power. Most operating systems (Linux/Unix/Mac) store the time on the hardware clock as UTC by default, though some systems (notably Microsoft Windows) store the time on the hardware clock as the ‘local’ time. This causes problems in a dual boot system if both systems view the hardware clock differently.

The advantage of having the hardware clock as UTC is that you don’t need to change the hardware clock when moving between timezones or when Daylight Savings Time (DST) begins or ends as UTC does not have DST or timezone offsets.

Changing Linux to use local time is easier and more reliable than changing Windows to use UTC, so dual-boot Linux/Windows systems tend to use local time.

Since Intrepid (8.10), UTC=yes is default.

Make Windows use UTC

Note: This method was not initially supported on Windows Vista and Server 2008, but came back with Vista SP2, Windows 7, Server 2008 R2 and Windows 8/8.1.

Note: Windows Time service will still write local time to the RTC regardless of the registry setting above on shutdown, so it is handy to disable Windows Time service with this command (if time sync is still required while in Windows use any third-party time sync solution):

Reversing the change

You can create a file with the following contents and then double-click it to merge in the original changes, as above:

If Windows Time service was disabled, enable it again with the command:

Make Linux use ‘Local’ time

To tell your Ubuntu system that the hardware clock is set to ‘local’ time:

Pre-Ubuntu 15.04 systems (e.g. Ubuntu 14.04 LTS):
  1. edit /etc/default/rcS
  2. add or change the following section
Ubuntu 15.04 systems and above (e.g. Ubuntu 16.04 LTS):
  1. open a terminal and execute the following command

Troubleshooting

Is NTP installed?

Run dpkg-query --list ntp\* and look for ntp-simple (pre 7.04) or ntp. The ntpdate and ntp-doc packages may also be useful.

Which configuration file is it using?

By default NTP uses /etc/ntp.conf. If /etc/ntp.conf.dhcp exists then the NTP daemon assumes you’re using DHCP to redefine the NTP settings and it uses that file instead.

How do I configure NTP to use DHCP

Your DHCP server must be configured to supply NTP servers (man dhcpd.conf may be helpful).

Your client must be configured to use the supplied NTP servers. To do this, add ntp-servers to the request (or even require) line in /etc/dhcp3/dhclient.conf. You may wish to use the default and prepend features as well to provide default/additional NTP servers. Please see man dhclient.conf and man dhcp-options for details.

Is NTP running?

NTP most commonly ‘fails’ if it cannot resolve the servers in its configuration file at startup (this can happen if DNS isn’t available during boot). Also, if NTP is unable to keep the local clock reasonably accurate it gives up and terminates (see below).

Try sudo /etc/init.d/ntp status to check if NTP is running, and sudo /etc/init.d/ntp restart to restart it if necessary.

I have various systems on unreliable networks so I use a simple script to bounce NTP if needed:

Which servers are you using?

Run grep ^server /etc/ntp.conf or grep ^server /etc/ntp.conf.dhcp to figure out which servers you’re trying to use

If your network or ISP have an NTP server they should be listed here. Failing that, try ntp.ubuntu.com and/or the NTP pool servers (http://www.pool.ntp.org/). 3 or 4 servers is plenty, and don’t use a server without permission (see http://en.wikipedia.org/wiki/NTP_vandalism).

Can these servers be resolved?

If host $servername fails then you may have DNS issues that need to be fixed ($servername is the name of a server listed in your configuration file, see above).

Can these servers be reached?

If ntptrace $servername fails then you may have routing/firewall issues that need to be fixed ($servername is the name of a server listed in your configuration file, see above). NTP uses UDP port 123, make sure these packets can are properly NAT-ed through your gateway if necessary.

What’s NTP up to?

ntpq --numeric --peers

—numeric removes the DNS lookups. You can leave it off, but don’t be surprised if the resolved names don’t match names in the ntp.conf file.

delay is in milliseconds. It should be < 1 for local network servers, < 10 for ISP servers over DSL and ideally < 100 for wireless. offset is in milliseconds and is the current best guess of the time difference between your system and the server. The smaller the better! jitter is an estimate the the local clock frequency error. The smaller the better. If it’s consistently high then your system may be drifting (see below)

Why does NTP keep resetting/failing?

NTP attempts to fix your local clock to keep accurate time. If your local clock drifts too fast (usually HW problems or IRQ lockups or somesuch) then NTP either keeps resetting your clock or gives up and terminates. Fix the drift problem and NTP will behave.

UbuntuTime (последним исправлял пользователь 1 2016-07-13 19:49:24)

The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *