Debian как изменить дату

Настройка даты и времени в Debian
Содержание

Введение
date: Узнать текущие системные дату и время
hwclock: Узнать текущие дату и время BIOS
Изменить дату и время вручную
Синхронизация с ntp
Заставить систему синхронизовать время с ntp
Timezone
Похожие статьи

Введение

При работе в сети синхронизация времени и даты это важный
фактор увеличивающий стабильность и

безопасность

работы всех систем.

В этой статье вы узнаете как настраивать дату и время вручную. И, что более
важно — как синхронизировать их с ntp сервером.

Узнать текущее системное время

Узнать текущее системное время можно командой
date

date

2023-02-09 11:49:51.364911+02:00

Узнать текущее время BIOS

Узнать текущее системное время BIOS можно командой
hwclock

sudo hwclock

2023-02-09 11:49:51.389911+02:00

date и hwclock
могут показывать совершенно разное время

Исправить текущее время

Сначала нужно задать время командой
date

date MMDDhhmmCCYY.ss

Описание параметров команды date:

MM две цифры текущего месяца (пример: январь=01);
DD две цифры текущей даты (если текущий календарный день 1, то пишется 01);
hh две цифры обозначающие час
mm две цифры обозначающие минуты
CCYY четыре цифры года
ss две цифры секунд

Также можно вводить «date MMDDhhmmCCYY» без секунд, тогда секунды выставляются на ноль.

После выполнения date нужно внести новое установленное время в BIOS:

hwclock —systohc

Теперь осталось только проверить сохранились ли изменения

sudo hwclock

Синхронизация с ntp

Проверьте установлен ли ntp командой

which ntpd

/usr/sbin/ntpd

Если ntp не установлен выполните

sudo apt install ntp

Проверьте запускается ли ntpd автоматически командой

systemctl list-unit-files | grep ntpd.s

ntpd.service enabled

Если ntpd неактивен (disabled) выполните

systemctl start ntpd

systemctl enable ntpd

Проверить добавлен ли сервис ntp в зону public в

firewall

можно командой

sudo firewall-cmd —get-services | grep ntp

Если ещё не добавлен, то чтобы разрешить UDP траффик от ntp выполните

firewall-cmd —permanent —add-service=ntp

firewall-cmd —reload

success

success

Отредактируйте файл

ntp.conf

с настройками сервера

vi /etc/ntp.conf

server 0.fi.pool.ntp.org
server 1.fi.pool.ntp.org
server 2.fi.pool.ntp.org
server 3.fi.pool.ntp.org

Теперь нужно перезапустить ntpd

systemctl restart ntpd

Проверить откуда берётся время можно командой

ntpq -p

remote refid st t when poll reach delay offset jitter
==============================================================================
time.cloudflare 10.79.8.177 3 u 14 64 7 3.987 -0.366 0.016
37.228.129.2 193.66.253.94 2 u 16 64 7 5.301 -1.639 1.908
ivanova.ganneff 237.17.204.95 2 u 13 64 7 5.296 3.850 0.266
ntp23.kashra-se 192.168.100.15 2 u 12 64 5 32.935 -2.213 0.192

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

hwclock —systohc

Заставить систему синхронизовать время с ntp

Можно следующей командой

sudo ntpdate -u 0.fi.pool.ntp.org

Вместо 0.fi.pool.ntp.org поставьте нужный вам сервер. Например, для России подойдёт один из

server 0.ru.pool.ntp.org

server 1.ru.pool.ntp.org

server 2.ru.pool.ntp.org

server 3.ru.pool.ntp.org

Timezone

Узнать текущую временную зону

timedatectl

Local time: Thu 2023-02-09 11:49:51. EEST
Universal time: Thu 2023-02-09 09:49:51 UTC
RTC time: Thu 2023-02-09 09:49:51
Time zone: Europe/Helsinki (EEST, +0300)
System clock synchronized: yes
NTP service: n/a
RTC in local TZ: no

Изменить временную зону можно командой set-timezone

timedatectl set-timezone «America/Denver»

Проверить результат

timedatectl | grep «Time zone»

Time zone: America/Denver (MDT, -0600)

Похожие статьи

Debian Linux
Установка Debian
Настройка сети в Debian
Firewall
Дата и время
X Window System Debian
Определить тип иксов
Загрузчик Grub2
Запись загрузочной флешки
Загрузка в безопасном режиме
PATH
FAQ
Ошибки
Grep

Date — утилита Unix/Linux для работы с системными часами. Если вызвать date без параметров, то будет выведена текущая дата и время, соответствующие текущему часовому поясу. Чтобы посмотреть время в часовом поясе UTC, используйте команду date —utc (или сокращенно date -u).
Необходимо следить за правильностью установки даты и времени, это нужно для корректной работы планировщика задач. Также, время и дата указывается во все основные системные лог-файлы и лог-файлы посещений веб-сервера.

Как изменить временную зону в Debian/Linux?
Нужно создать симлинк из /etc/localtime на «нужный» файл из каталога /usr/share/zoneinfo/:

# ln -sf /usr/share/zoneinfo/Europe/Moscow /etc/localtime

Также советую изменить соответствующую запись в /etc/timezone

Как изменить дату и время в Debian/Linux?

# date MMDDhhmmYYYY.ss
MM — месяц
DD — день
hh — час
mm — минуты
YYYY — год
ss — секунды

Как изменить время в Debian/Linux?

# date —set hh:mm

Синхронизация времени в Linux/Ubuntu. NTP и Ntpdate.
NTP — это протокол синхронизации времени по сети.
Сервис NTP ntpd вычисляет насколько отстают ваши часы и постоянно подправляет их, благодаря этому не происходит сильных изменений, что может приводить к непоследовательности в журналах. Этот сервис не требует много ресурсов, поэтому его можно установить не задумываясь.
Для установки ntpd из консоли введите:

# apt-get install ntp

Конфигурация находится в файле /etc/ntp.conf, тут можно добавлять и удалять сервера, с которыми нужно синхронизировать время.
По умолчанию сервера в Ubuntu выглядят так:

pool 0.ubuntu.pool.ntp.org iburst
pool 1.ubuntu.pool.ntp.org iburst
pool 2.ubuntu.pool.ntp.org iburst
pool 3.ubuntu.pool.ntp.org iburst

Если вы добавите свои сервера, то нужно перезапустить сервис ntpd для применения изменений:

# service ntp restart

It is very essential to have your system configured with the proper date and time. Mostly the Debian OS uses NTP to synchronize time over a network. However, sometimes, you need to manually set the date and time in your system.

In this post, we will show how to change the date, time, and timezone in your Debian system. Debian OS allows you to change your system date, time, and timezone through the following two methods:

  • Through Command Line
  • Through GUI

Note: Before proceeding, it’s worth mentioning that all the commands and procedures shown in this post have been tested on Debian 10 (Buster).

Changing the Date, Time, and Timezone through Command Line

The “timedatectl” command is used to view and change the current date, time, and timezone of a system. Let’s get started:

View Current Date, Time, and Timezone

To view the current date, time, and timezone, you can either use the “date” or “timedatectl” command.

Using the “date” command

In order to view the current date, time, and timezone, simply execute the date command in Terminal:

$ date

This command shows the day of the week, month name, day of the month, time, timezone name, and year:

date, time and timezone

Using the “timedatectl” command

In order to view the current date, time, and timezone, simply execute the timedatectl command in Terminal:

$ timedatectl

This command displays the local time as well as the universal and RTC time. It also displays complete information about the timezone.

To find your system’s current time information, view the first line of output. This line displays the day of the week, date, time, and timezone information.

date, time and timezone

If you notice in the above screenshot, the NTP service is “active”. For manually configuring the date, time, and timezone in your Debian system, you will need to turn off the NTP service. Run the following command in Terminal to do so:

$ timedatectl set-ntp no

Now again run the timedatectl command to view if the service status has changed to “inactive”.

timedatectl command

Changing the Date

In order to change the date in the Debian system, run the timedatectl command using the following syntax:

$ timedatectl set-time YYYY-MM-DD

In the above command,

  • “YYYY” represents the year
  • “MM” represents the month (01-12)
  • “DD” represents (01-31)

In order to set the date to let’s say: 2020-12-26 (26th December 2020), the command would be:

$ timedatectl set-time 2020-12-26

changing date

Once you have set the date, run the following command to view if it has changed successfully:

$ timedatectl

The following output shows the date has been changed to our desired value 2020-12-26. view current date

Changing the Time

In order to change the time in the Debian system, run the timedatectl command using the following syntax:

$ timedatectl set-time hh-mm-ss

In the above command,

  • “hh” represents hours (00-24)
  • “mm” represents minutes (00-59)
  • “ss” represents seconds (00-59)

In order to set the time to let’s say: 18:40 (or 6:40 pm), the command would be:

$ timedatectl set-time 18:40

change time

Once you have changed the time, run the following command to view if it has changed successfully:

$ timedatectl

The following output shows the time has been changed to our desired value 18:40.

view time

Changing the Timezone

Similar to date and time, the timezone can also be changed using the timedatectl command. Before changing the timezone, you can list available timezones as follows:

$ timedatectl list-timezones

This command lists all the available timezones from which you can choose your desired timezone name.

list timezones

In order to change the timezone in the Debian system, run the timedatectl command using the following syntax:

$ timedatectl set-timezone geographical region/city

For instance, to change the timezone to Asia/Dubai, the command would be:

$ timedatectl set-timezone Asia/Dubai

Once you have changed the timezone, run the following command to view if it has changed successfully:

$ timedatectl

The following output shows the timezone has been successfully changed to Asia/Dubai.

view current timezone

Changing the Date, Time, and Timezone through GUI

For users who prefer working with GUI, here is how they can change the date, time, and timezone in their Debian system.

View Current Date, Time, and Timezone

In order to view the current date, time, and timezone, hit the super key on the keyboard and type date & time. Then from the search results, click Date & Time.

date and time

It opens the Settings utility in the Date & Time view. Here you can see your system’s current date, time, and timezone information.

Settings utility

Changing Date and Time

For changing the date and time, first, make sure the Automatic Date & Time switch is turned off. Now in order to change the date and time, click the Date and Time option as shown in the following screenshot:

daet and time

The following Date & Time window will appear for you to manually choose the date and time. Once you have set the desired date and time, close the window.

changing date and time

Using the Time Format option, you can choose 24-hour or AM/PM time format.

change tiem format

Changing Timezone

For changing the timezone, first, make sure the Automatic Time Zone switch is turned off. Now in order to change the timezone, click TimeZone as shown in the following screenshot.

timezone

By clicking the TimeZone, you will see the following window with the map. Choose your location on the map or you can also use the search bar at top to search for your location. Once you do it, your timezone will be changed. After that, close the window.

change timezone

By following the procedures discussed in this post, you can easily change the date, time, and timezone in your Debian system. Based on your convenience, you can either choose the command line or the GUI method. If you are using Ubuntu OS, you can visit our post on How to Change the Date, Time, and Timezone in Ubuntu 20.04 LTS.

Maryam-Sulemani

Ummara Mushtaq is a Telecommunication engineer with two years of experience in server support and networking. She writes technical articles based on Linux system administration for LinuxWays.

Я использую операционную систему Debian GNU/Linux на серверах для хостинга сайтов. Когда летом 2017 года вышла версия 9 Stretch, я обрадовался тому, что для нее в репозиториях «из коробки» был доступен PHP 7. Который, как известно, работает быстрее PHP 5.

В этой статье я покажу, что и с настройкой времени на Debian 9 так же стало лучше, не нужно ничего качать и устанавливать дополнительно, в частности демон ntp или утилиту ntpdate. Все отлично настраивается и работает на стандартном наборе ПО Debian 9 благодаря обновлённой версии systemd, в котором имеется отдельная служба, отвечающая за синхронизацию времени системы по протоколу NTP.

Как настроить время Debian 9

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

# timedatectl set-timezone Europe/Volgograd

Вместо Europe/Volgograd вы должны использовать свои данные, список доступных значений часовых поясов можно посмотреть здесь — https://timezonedb.com/time-zones

Затем нужно отредактировать файл /etc/systemd/timesyncd.conf, указав в нем серверы для синхронизации времени, например так:

#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation; either version 2.1 of the License, or
#  (at your option) any later version.
#
# Entries in this file show the compile time defaults.
# You can change settings by editing this file.
# Defaults can be restored by simply deleting this file.
#
# See timesyncd.conf(5) for details.

[Time]
NTP=ru.pool.ntp.org
FallbackNTP=pool.ntp.org

Здесь в опции NTP= указываются приоритетные серверы для синхронизации времени. Если при обращении к ним произойдет сбой, то будут использоваться серверы, указанные в FallbackNTP=.

В качестве серверов для синхронизации времени лучше выбрать те, что ближе к вам находятся, например континентальные или соответствующие вашей стране (в частности, ru.pool.ntp.org для России, ua.pool.ntp.org для Украины и т.д.). Подробнее можно почитать здесь — https://www.ntppool.org/ru/use.html

После внесения изменений в файл конфигурации нужно перезапустить сервис синхронизации времени:

# systemctl restart systemd-timesyncd

Состояние настройки времени можно проверить следующей командой:

# timedatectl status

Результат ниже говорит о том, что часы на моем сервере настроены верно и синхронизируются по протоколу NTP.

      Local time: Tue 2018-12-18 16:36:33 +04
  Universal time: Tue 2018-12-18 12:36:33 UTC
        RTC time: Tue 2018-12-18 12:36:33
       Time zone: Europe/Volgograd (+04, +0400)
 Network time on: yes
NTP synchronized: yes
 RTC in local TZ: no

здесь,
Local time — это местное время;
Universal time — время UTC (всемирное координированное время). Это отправная точка для отсчета всех часовых поясов;
RTC time — время в аппаратных часах сервера (компьютера);
Time Zone — ваш часовой пояс;
Network time on — указывает, включен ли ntp-клиент, входящий в состав systemd;
NTP synchronized — сообщает, синхронизировано ли время с ntp-сервером;
RTC in local TZ — показывает, какое время хранится в аппаратных часах: локальное или всемирное. При этом, yes означает локальное время, no — всемирное;

Информация для новичков

Меня иногда спрашивают, где вводить (выполнять) приводимые мною команды?

Все приведенные в данной статье команды нужно выполнять в консоли сервера от имени привилегированного пользователя (root). Знак # (октоторп, решетка, диез, хеш) как раз говорит об этом.

В качестве консольного клиента для удаленного подключения к серверам я использую программу PuTTY. Это бесплатный SSH и Telnet клиент для Windows и Unix платформ.

Выводы о настройке времени в Debian 9

В отличии от предыдущих версий в Debian 9 все просто, не нужно устанавливать никаких дополнительных программ. Синхронизация времени работает «из коробки» и настраивается за 2 минуты.

Благодарности

При написании статьи были использованы следующие источники:

  1. https://evlanoff.wordpress.com/2017/11/22/changing-timezone-debian-9/
  2. https://wiki.it-kb.ru/unix-linux/debian/stretch/systemd-timesyncd-in-debian-9
  3. http://www.linuxrussia.com/systemd-useful-tools.html

Содержание

  1. Debian GNU/Linux System Administrator’s Manual (Obsolete Documentation) Chapter 16 — Time
  2. 16.1 Setting time, time zones and Daylight Saving
  3. 16.1.1 Changing the timezone after installation
  4. 16.1.2 Setting the TZ environment variable.
  5. 16.2 Setting and showing hardware clock
  6. 16.3 Multiboot with operating systems not understanding timezone
  7. 16.4 Syncing time, rdate and NTP
  8. 16.4.1 Setting time at system boot
  9. 16.4.2 Setting time using NTP
  10. 16.4.3 Other methods
  11. 16.5 Setting up an NTP server
  12. 16.6 Radio clocks
  13. 16.7 Timestamps
  14. 16.8 Time in cron
  15. Изменение даты, времени, временной зоны в Debian/Linux

Debian GNU/Linux System Administrator’s Manual (Obsolete Documentation)
Chapter 16 — Time

Computers have a clock to keep time. Usually there is a hardware clock with battery backup to keep time when the computer is off. The operating system (for example Linux) runs its own clock, and from this clock comes the time shown by commands such as date in Linux and time in DOS.

The hardware clock is usually accurate enough, provided that the battery has not run out. If the time shown by the computer when you turn it on is wrong by several months or years, it is worth checking if the battery is still usable.

The «software» clock in the operating system usually has drift, either systematic or random. This drift means the clock runs too fast or too slow. For this reason it is nesessary to use some accurate time source to syncronize the operating system clock if accurate time is needed.

To see the time on Debian GNU/Linux, use the command date . For example

The above command shows the day of the week, the month, the day of the month, the time, the time zone and the year. The time zone also shows whether Daylight Saving Time is in use (in the example, the base time zone is EET,and the extra S means Saving).

In Debian GNU/Linux and other Unix, the command time does not show time. It is used to time command excecutions. If you have some command that takes a fair amount of time to execute, and you do not feel like standing by with a stopwatch, you can see how long it took by running the command as argument to time . This example may clear things up:

If You have root privileges, you can also change the time with the command date (see the man page date(1) ). If you are connected to the Internet or have other Unix computers on your LAN, see Syncing time, rdate and NTP, Section 16.4 for easier ways to set time.

When setting the time manually, the time string may be confusing. The command date —set accepts the date and time in many formats. You can read the sh-utils info document, or use the example below to figure out one possible format. There date is given in ISO 8601 standard format YYYY-MM-DD for Year-Month-DayOfMonth, and time of day using 24 hour clock. Leading zeros are significant.

The above two commands set the date to 2nd November 1998, and time to eight minutes past 9pm.

To see the time in UTC, use command date -u .

If you are running X Window, you may have a clock display somewhere on the screen. If not, you can obtain it by running the command xclock , which is part of the xbase package. The bare xclock command gives you an analog clock (with big hand, little hand, and an optional seconds hand). You can get a digital clock (with xclock -digital ). See the man page xclock(1) for more information.

16.1 Setting time, time zones and Daylight Saving

When you installed the base system of Debian GNU/Linux, you set the Timezone. You can check how you have set the Timezone by looking at the file /etc/timezone . If you want to change the timezone configuration, see Changing the timezone after installation, Section 16.1.1.

The time zone is needed because Unix computers keep time in Universal Time (UTC), and local time is calculated from this. UTC is solar time on meridian 0. UTC was previously called Greenwich Mean Time (GMT) because meridian 0 passes through the old Royal Observatory in Greenwich, which is part of London, England.

UTC is constant, and is not subject to Daylight Saving Time or other changes. This is what makes it useful for syncronising computers. As long as the base time is kept in UTC, computers all over the world can be synchronised and yet maintain their local time information.

If you were to set your Debian GNU/Linux computer to use local time, without taking account of timezones, you would lose the benefit of automatic DST changes. We do not recommend this! However, it may be necessary to compromise by setting your hardware clock to local time (see Multiboot with operating systems not understanding timezone, Section 16.3). In this document, we assume that you have configured your computer to use UTC.

To change the computer to use UTC after installation, edit the file /etc/default/rcS , change the variable UTC to no . If you happened to install your system to use local time, just change the variable to yes to start using UTC. It is best to reboot after editing /etc/default/rcS to get the changes effective.

If the Timezone is correctly set up, and the timezone configuration files are reasonably current, the local time shown by the operating system will change to Daylight Saving Time and back to normal time automatically on the correct dates. If the timezone files you have are old, there may be problems because DST start and end dates are not determined by a physical phenomenon, but are chosen by national institutions. Sometimes these dates are changed, for example, the European Union changed the end date from the last Sunday in September to the last Sunday in October in 1995.

For this reason, you should make sure that your libc6 package is kept reasonably up to date. This package, from Debian GNU/Linux 2.2 onwards, contains the timezone data.

16.1.1 Changing the timezone after installation

If the timezone is not set or is wrong, the superuser can run tzconfig to configure it after the operating system is installed (see man page tzconfig(8) ).

If there are other users, it is a good idea to notify then that the system Timezone has changed.

16.1.2 Setting the TZ environment variable.

If you do not have root privileges or want to set for yourself a different timezone than the one the system uses, you can set the environment variable TZ . Use the command tzselect to show what value to use for TZ.

Example on using TZ:

As you can see, for this user date shows a different time. (but this seems wrong, since Pacific Standard Time should be 09:49. What’s happening. ).

16.2 Setting and showing hardware clock

The command for setting the hardware clock is hwclock . (This was not in Debian before 2.0. In earlier releases, the command was clock .)

If you use the date command to change time, it is worth setting also the hardware clock to the correct time. Otherwise, the time is wrong after the next reboot, since the hardware clock keeps the time when power is turned off. When the clock in the operating system shows the correct time, set the hardware clock like this:

Remember to add the —utc -option if the hardware clock is set to UTC!

See man page hwclock(8) for more information.

At least from Debian version 2.2 onwards, the system automatically saves the system time to hardware clock on shutdown, and sets the system clock from hardware clock when Debian boots up. This is done in the script /etc/init.d/hwclock.sh .

16.3 Multiboot with operating systems not understanding timezone

If you have a multiboot configuration, where you have some other operating system(s) on the same computer, and during boot choose which one to start, you may get confused about the correct time. If the other operating systems do not understand timezones, they think UTC is the local time and show the wrong time (unless you live in London, England or some other place in the same timezone).

DOS, OS/2 and Windows except NT do not use timezones. If you need to have the correct local time in these operating systems, you have to set the clock to local time. Debian Linux can live with this and it works, but if your main operating system(s) understand timezones, use them.

16.4 Syncing time, rdate and NTP

If you have another Unix computer which you know keeps the correct time, with root privileges you can set the time with the command rdate . For example:

Even if you do not have an accurate time source, it is still a good idea to set all your computers to the same time, so that you can compare time stamps between hosts. To keep the clocks syncronized, You can start rdate once daily from cron.

16.4.1 Setting time at system boot

If the hardware clock does not keep the correct time, it is possible to set the correct time when the operating system boots. For this, there must be some other host in the LAN where the time can be received. Here is an example:

create the file /etc/init.d/rdate

Create a symbolic link to that file in directory /etc/rc2.d

At next reboot, you should see the time being set.

Remember to set execute permission to /etc/init.d/rdate . If You are wondering what the number S19 above means, read chapter . The key is to run rdate after netbase which starts networking, and before xntp3 or some other process where time is needed starts.

16.4.2 Setting time using NTP

If you are connected to the Internet, you can install an NTP client, for example ntp or xntp3 in Debian version 2.1 and older. This uses the Network Time Protocol RFC 1305 to synchronise clocks to a few tens of milliseconds precision. If you need this kind of precision or better, see also Radio clocks, Section 16.6.

See the excellent documentation that comes with ntp , in the Debian package ntp-doc . It is very thorough and thus long. If you think reading documents is a waste of time, just ask your Internet Service Provider or system administrator for NTP server names, or look up the nearest one in «List of Public NTP Servers» in http://www.eecis.udel.edu/

mills/ntp/servers.html . If you start using an NTP server, it is usually polite to notify the server’s administrator of the fact.

Do not configure your system to query level 1 NTP servers! If you think you need to do this, you are almost certainly wrong!

Once you know an NTP server, edit the file /etc/ntp.conf to add at least one server line. Here is an example:

Note, that I changed the actual server name in the above example, to prevent all Debian GNU/Linux users from blindly using that one server. Everything else except the server lines was there after xntp3 installation.

If you do not have a permanent Internet connection, then running NTP client is not a good solution. NTP client syncronizes relatively often, and needs the Internet connection to be always on. If you have a dial up Internet connection, you can run the command ntpdate (also in ntp package) to syncronize each time you connect.

Another possibility is to set cron to run ntpdate once daily, this gives good accuracy for most uses. The following is an example script that can be started from cron and runs ntpdate . This scripts assumes the /etc/ntp.conf is correctly set up, since it gets the server names from that file.

16.4.3 Other methods

Debian GNU/Linux has also the command netdate , see man page netdate(8L) for more info. It uses the protocol defined in RFC 868.

16.5 Setting up an NTP server

If you have several hosts that you want to synchronise, you should not let them all separately synchronise to an outside NTP server. This puts a load on the NTP server, and if it is a public and free service, the people there may start to dislike you! At least ask if it is OK to sync all of your machines there.

A better way is to set up one of your hosts as an NTP server, sync that to the outside NTP server and the rest of your hosts to your own NTP server. The ntp package provides the server component as well, so you just need to configure it. This is not particularly difficult either, but you should read the documentation and understand the peer concept and stratum hierarchy.

16.6 Radio clocks

If you want better accuracy or cannot synchronise with an NTP server in the public Internet, you can purchase a radio clock. These get the time from time servers that use a very accurate clock, and broadcast time signals using radio waves.

There are radio clocks that need a ground based transmitter near enough to get the signal. If you get one of these, make sure you can receive the signal on the location where you plan to use it. The transmitters are ground based, so they don’t work accross the globe.

Another kind of radio clock uses a Global Positioning System GPS receiver. GPS satellites circle the globe in low earth orbits, and there should always be at least four above the horizon. They are mainly used for navigation, but the principle they work on is based on sending time signals. For time synchronisation it is enough to get the signal from one satellite, but usually it is necessary to install the GPS antenna outdoors to get good reception.

16.7 Timestamps

Timestamps in files are in UTC. The command ls -l shows file timestamps in local time using the Timezone in effect. Because timestamps are in UTC, timestamps can be compared between separate computers. This can lead to problems if the clocks are not syncronized.

Consider this situation: You log in host B, which NFS loads your home directory from NFS server host A. You edit some file, save it and start make . If the clocks in hosts A and B are not syncronized, make may complain that the file modification time is in the future, or not compile the file because the object is newer.

16.8 Time in cron

The times in cron are local times. This means, that if you configure cron to start some program at 7 in the morning, it is 7 in the morning local time as determined by the system Timezone.

This causes headaches, if the system Timezone is not the same you have set for yourself using the TZ enviroment variable, or you have two host in different Timezones that need to start someting at the same time on both hosts.

Debian GNU/Linux System Administrator’s Manual (Obsolete Documentation)

Источник

Изменение даты, времени, временной зоны в Debian/Linux

Date — утилита Unix/Linux для работы с системными часами. Если вызвать date без параметров, то будет выведена текущая дата и время, соответствующие текущему часовому поясу. Чтобы посмотреть время в часовом поясе UTC, используйте команду date —utc (или сокращенно date -u).
Необходимо следить за правильностью установки даты и времени, это нужно для корректной работы планировщика задач. Также, время и дата указывается во все основные системные лог-файлы и лог-файлы посещений веб-сервера.

Как изменить временную зону в Debian/Linux?
Нужно создать симлинк из /etc/localtime на «нужный» файл из каталога /usr/share/zoneinfo/:

Также советую изменить соответствующую запись в /etc/timezone

Как изменить дату и время в Debian/Linux?

Как изменить время в Debian/Linux?

Синхронизация времени в Linux/Ubuntu. NTP и Ntpdate.
NTP — это протокол синхронизации времени по сети.
Сервис NTP ntpd вычисляет насколько отстают ваши часы и постоянно подправляет их, благодаря этому не происходит сильных изменений, что может приводить к непоследовательности в журналах. Этот сервис не требует много ресурсов, поэтому его можно установить не задумываясь.
Для установки ntpd из консоли введите:

Конфигурация находится в файле /etc/ntp.conf, тут можно добавлять и удалять сервера, с которыми нужно синхронизировать время.
По умолчанию сервера в Ubuntu выглядят так:

Если вы добавите свои сервера, то нужно перезапустить сервис ntpd для применения изменений:

Источник

В статье мы разберёмся с тем, как настроить время в Linux. Посмотрим текущее время, укажем часовой пояс и настроим синхронизацию времени.

Чтобы посмотреть текущее время на вашем сервере linux воспользуйтесь командой date:

alex@ubu:~$ date
Ср 13 июл 2022 13:40:27 UTC

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

Также можно использовать другую команду – timedatectl:

alex@s-ubu:~$ timedatectl
               Local time: Ср 2022-07-20 07:56:41 UTC
           Universal time: Ср 2022-07-20 07:56:41 UTC
                 RTC time: Ср 2022-07-20 07:56:41
                Time zone: UTC (UTC, +0000)
System clock synchronized: yes
              NTP service: active
          RTC in local TZ: no

Без опций она покажет текущее время, часовой пояс, а также другую информацию связанную с синхронизацией времени. Например в примере выше видно что время успешно синхронизуется (System clock synchronized: yes) и синхронизация настроена (NTP service: active).

С помощью этой же утилиты (timedatectl) мы будем настраивать часовой пояс и следить за синхронизацией времени, об этом чуть ниже.

Настройка часового пояса

Вообще часовой пояс в системе определяется файлом /etc/localtime, который является символьной ссылкой (про ссылки я уже писал):

alex@ubu:~$ ls -l /etc/localtime
lrwxrwxrwx 1 root root 27 апр 21 01:01 /etc/localtime -> /usr/share/zoneinfo/Etc/UTC

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

alex@ubu:~$ sudo ln -sf /usr/share/zoneinfo/Europe/Moscow /etc/localtime

Или воспользоваться утилитой timedatectl:

alex@ubu:~$ sudo timedatectl set-timezone Europe/Moscow

Если вас не устраивает выбранный мною часовой пояс, то можете посмотреть список поддерживаемых часовых поясов так:

alex@ubu:~$ timedatectl list-timezones

Проверим время и часовой пояс:

alex@ubu:~$ timedatectl
               Local time: Ср 2022-07-13 16:50:39 MSK
           Universal time: Ср 2022-07-13 13:50:39 UTC
                 RTC time: Ср 2022-07-13 13:50:39
                Time zone: Europe/Moscow (MSK, +0300)
System clock synchronized: yes
              NTP service: active
          RTC in local TZ: no

Как видим, часовой пояс уже изменился на Europe/Moscow (MSK, +0300).

Синхронизация времени

В настоящее время очень важно чтобы часы на ваших серверах были синхронизированы. Очень много систем полагаются на время, например:

  • если часы на сервере kerberos и клиенте расходятся более чем на 5 минут, то клиенты не смогут пройти проверку подлинности на сервере;
  • в различных финансовых системах транзакции должны выполняться в надлежащем порядке, поэтому серверы выполняющую эту работу должны быть строго синхронизированы по времени;
  • правильное время также нужно для выполнения автоматизированный задач;
  • системные журналы также полагаются на время.

Получение списка NTP серверов по DHCP

Если ваш сервер получает сетевые настройки по dhcp, то он может получить список NTP серверов (серверов времени для синхронизации). Это настраивается в файле /etc/dhcp/dhclient.conf. В строке request мы определяем что хотим получать от сервера dhcp. И здесь может быть указан параметр ntp-servers:

alex@ubu:~$ cat /etc/dhcp/dhclient.conf
# часть текста пропустил
request subnet-mask, broadcast-address, time-offset, routers,
        domain-name, domain-name-servers, domain-search, host-name,
        dhcp6.name-servers, dhcp6.domain-search, dhcp6.fqdn, dhcp6.sntp-servers,
        netbios-name-servers, netbios-scope, interface-mtu,
        rfc3442-classless-static-routes, ntp-servers;
# часть текста пропустил

Само собой, вы получите список ntp-серверов, только в том случае если ваш dhcp сервер их распространяет.

Служба синхронизации времени

В системах работающих на systemd работает специальная служба синхронизации времени systemd-timesyncd.service. Можем посмотреть её статус:

alex@ubu:~$ systemctl status systemd-timesyncd.service
● systemd-timesyncd.service - Network Time Synchronization
     Loaded: loaded (/lib/systemd/system/systemd-timesyncd.service; enabled; vendor preset: enabled)
     Active: active (running) since Wed 2022-07-13 17:08:06 MSK; 23s ago
       Docs: man:systemd-timesyncd.service(8)
   Main PID: 399 (systemd-timesyn)
     Status: "Initial synchronization to time server 192.168.0.16:123 (192.168.0.16)."
      Tasks: 2 (limit: 2241)
     Memory: 1.3M
        CPU: 63ms
     CGroup: /system.slice/systemd-timesyncd.service
             └─399 /lib/systemd/systemd-timesyncd

Видим что синхронизация идет с сервером по адресу 192.168.0.16. У меня этот адрес прилетел по dhcp.

Обратите внимание, что служба эта стартует по запросу и останавливается после синхронизации времени!

Давайте выключим получение ntp серверов по dhcp:

alex@ubu:~$ sudo nano /etc/dhcp/dhclient.conf
# в этой строке удалите опцию ntp-servers
request subnet-mask, broadcast-address, time-offset, routers,
        domain-name, domain-name-servers, domain-search, host-name,
        dhcp6.name-servers, dhcp6.domain-search, dhcp6.fqdn, dhcp6.sntp-servers,
        netbios-name-servers, netbios-scope, interface-mtu,
        rfc3442-classless-static-routes;

Вы можете использовать следующий пул серверов времени для синхронизации – https://www.pool.ntp.org/zone/ru. Укажем первый сервер из этого пула в конфиге /etc/systemd/timesyncd.conf:

alex@ubu:~$ sudo nano /etc/systemd/timesyncd.conf
[Time]
NTP=0.ru.pool.ntp.org
FallbackNTP=ntp.ubuntu.com
RootDistanceMaxSec=5
PollIntervalMinSec=32
PollIntervalMaxSec=2048

В конфиге используются следующие опции:

  • NTP – укажите 1 или несколько ntp серверов. Если хотите указать несколько серверов, разделяйте их пробелами;
  • FallbackNTP – укажите 1 или несколько резервных ntp серверов;
  • RootDistanceMaxSec – максимальное время в секундах, за которое пакет от сервера эталонного времени должен доходить до сервера к которому мы подлкючены;
  • PollIntervalMinSec и PollIntervalMaxSec – минимальный и максимальный интервалы синхронизаций времени. Вначале используется минимальный интервал, а затем он увеличивается если система видит что локальное время со временем ntp-сервера не расходится.

После правки перезапустите службу синхронизаций времени:

alex@ubu:~$ sudo systemctl restart systemd-timesyncd.service

Дополнительно можно посмотреть информацию по синхронизации времени с помощью следующей команды:

alex@ubu:~$ timedatectl timesync-status
       Server: 91.209.94.10 (0.ru.pool.ntp.org)
Poll interval: 34min 8s (min: 32s; max 34min 8s)
         Leap: normal
      Version: 4
      Stratum: 2
    Reference: 3EE70662
    Precision: 1us (-25)
Root distance: 4.012ms (max: 5s)
       Offset: -5.502ms
        Delay: 11.084ms
       Jitter: 2.886ms
 Packet count: 7
    Frequency: +15,118ppm

Здесь мы видим адрес ntp-сервера, а также какой интервал синхронизации (34min 8s) использовался последний раз.

То-есть служба синхронизации времени systemd-timesyncd.service будет запускаться и останавливаться сейчас примерно раз в 34 минуты. Поэтому если увидите, что служба в состоянии loaded и inactive, не пугайтесь. По логам видно что она периодически запускается:

alex@ubu:~$ systemctl status systemd-timedated
○ systemd-timedated.service - Time & Date Service
     Loaded: loaded (/lib/systemd/system/systemd-timedated.service; static)
     Active: inactive (dead)
       Docs: man:systemd-timedated.service(8)
             man:localtime(5)
             man:org.freedesktop.timedate1(5)

июл 19 15:54:24 s-ubu systemd[1]: systemd-timedated.service: Deactivated successfully.
июл 19 15:55:41 s-ubu systemd[1]: Starting Time & Date Service...
июл 19 15:55:41 s-ubu systemd[1]: Started Time & Date Service.
июл 19 15:56:35 s-ubu systemd[1]: systemd-timedated.service: Deactivated successfully.
июл 19 16:05:45 s-ubu systemd[1]: Starting Time & Date Service...
июл 19 16:05:45 s-ubu systemd[1]: Started Time & Date Service.
июл 19 16:06:15 s-ubu systemd[1]: systemd-timedated.service: Deactivated successfully.
июл 19 16:28:42 s-ubu systemd[1]: Starting Time & Date Service...
июл 19 16:28:42 s-ubu systemd[1]: Started Time & Date Service.
июл 19 16:30:17 s-ubu systemd[1]: systemd-timedated.service: Deactivated successfully.

Из вывода:

  • Deactivated successfully – служба останавливается;
  • Starting Time & Date Service… – служба стартует;
  • Started Time & Date Service – служба стартовала;
  • и так по кругу.

Ещё один способ задать часовой пояс

С помощью команды dpkg-reconfigure tzdata также можно задать часовой пояс:

alex@ubu:~$ sudo dpkg-reconfigure tzdata

После выполнения вы можете использовать псевдографический интерфейс для настройки часового пояса. Вначале выберите географический район:

dpkg-reconfigure tzdata - выбор географического района

dpkg-reconfigure tzdata – выбор географического района

Затем город:

dpkg-reconfigure tzdata - выбор города

dpkg-reconfigure tzdata – выбор города

Итог

Теперь вы знаете как настроить время на сервере Debian или Ubuntu. Мы научились устанавливать часовой пояс и настраивать синхронизации времени с ntp серверами.

Узнали про следующие команды:

  • date – покажет текущую дату, время и часовой пояс;
  • timedatectl – покажет тоже самое что и date + синхронизуется ли время;
  • timedatectl list-timezones – покажет список поддерживаемых часовых поясов;
  • timedatectl set-timezone Europe/Moscow – установить часовой пояс Europe/Moscow;
  • timedatectl timesync-status – покажет с какими ntp-серверами синхронизуется время и как часто;
  • dpkg-reconfigure tzdata – установить часовой пояс.

Познакомились с файлами:

  • /etc/localtime – является символической ссылкой и содержит информацию о текущем часовом поясе;
  • /etc/dhcp/dhclient.conf – настройки dhcp-клиента, который умеет запрашивать ntp-сервера для синхронизации времени;
  • /etc/systemd/timesyncd.conf – настройки службы синхронизации времени.

Узнали про службу синхронизации времени:

  • systemd-timedated.service – стартует по запросу, а после синхронизации времени отключается до следующей синхронизации.

Сводка

Дата, время и часовой пояс в Linux

Имя статьи

Дата, время и часовой пояс в Linux

Описание

В статье мы разберёмся с тем, как настроить время в Linux. Посмотрим текущее время, укажем часовой пояс и настроим синхронизацию времени

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Debian make error 2
  • Debian lightdm error getting user list from org freedesktop accounts
  • Debian gpg error keyexpired
  • Debian fontconfig error cannot load default config file
  • Debian exec format error

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии