Как изменить время на raspberry pi
Перейти к содержимому

Как изменить время на raspberry pi

  • автор:

Add a real-time clock to your Raspberry Pi

The Raspberry Pi keeps track of time by checking the internet, which becomes problematic when no internet connection is available. In this guide I explain how to add a real-time clock.

Table of contents

Time keeping

Because the Raspberry Pi is designed as an ultra-low cost computer, it lacks the little coin-battery-powered ‘Real Time Clock’ (RTC) module that sits in your laptop or desktop computer. Instead, the Raspberry Pi updates the time automatically from the global ntp (nework time protocol) servers. This can be a problem for stand-alone projects with no network connection, as your Raspberry Pi will not be able to accurately keep the time. There are various inexpensive add-on RTC boards available that simply plug on top of the Raspberry Pi’s GPIO pins.

Setting-up I2C

Any RTC uses the I2C protocol to communicate with the Raspberry Pi. So the first thing to enable a RTC is to set up I2C. To do so, run the following command:

Make sure I2C is enabled by going to Preferences > Raspberry Pi Configuration > Interfaces > click Enable next to i2c , and click OK . Now turn off your Raspberry Pi ( sudo halt ).

Setting up the RTC

Now plug your RTC board onto your Raspberry Pi GPIO pins. Here we will be setting up the DS1307 Real Time Clock, but many others exist (e.g. this list). Verify that the board is connected successfully by running:

You should see ID #68 show up:

i2c sensor

Using the RTC

Before the RTC module can be used, we need to run a couple more commands. First, the RTC module must be loaded by the kernel:

Next, add the RTC kernel to the /etc/modules file so it is loaded when it boots:

adding rtc-ds1307 at the end of the file.

Now add the device creation at boot by editing the rc.local file:

making sure to include the following lines just before exit 0 :

If you now reboot, the Raspberry Pi should have the correct time from the hardware RTC.

Commands for using the RTC

To read the time from the hardware RTC:

To copy the time from the Raspberry Pi system to the Hardware RTC:

To copy the time from the hardware RTC to the Raspberry Pi:

Comments

There are currently not any comments yet.

Add a Comment

Please leave your comment below. If you’d like to be notified of my reply, please leave your comment here for others but also send your comment as an email to me. I will try to reply as soon as I can. Thanks!

Выставляем время через консоль

В этой ветке форума я попробую собрать множество интересных команд, которые помогут вам более глубоко разобраться в настройках такой замечательной платформы как Raspberry Pi. И начну с самого основного — выставление времени.
Данный процесс очень важен с точки зрения путешествия по глобальному информационному пространству, т.к. к примеру такие поисковые системы как google для выдачи сертификата доступа смотрят непосредственно на текущее время вашей системы. Если оно выставлено неправильно — вам соответственно будет отказано в доступе к данному ресурсу. Но исправить это легко с помощью следующей команды.

1. Включим терминал нажав соответствующую кнопку / или сочетание клавиш Ctrl+Alt+T.
2. Введём команду:

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

К примеру что бы выставить текущую актуальную дату я записал следующую команду: date 011910322017.00, что значит месяц 01 — январь, 19 число, 10 часов, 32 минуты, 2017 год, и 00 секунд.

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

sudo apt install ntp
sudo systemctl enable ntp
sudo timedatectl set-ntp 1

При данном подходе желательно настроить часовой пояс в основных настройках Raspberry Pi Configuration.

How to Set Time and Date on Raspberry Pi

If you want to set a time and date on your Raspberry Pi system, you should follow article guidelines.

Setting up Time and Date on Raspberry Pi

There are two simple methods to set up time and date on Raspberry Pi.

Method 1: Set Time and Date on Raspberry Pi from Raspberry Pi Configuration

If a user wants to set up the time and date on Raspberry Pi through this method, he/she needs to follow the following steps:

Step1: Open the Raspberry Pi terminal and type the below-mentioned command to go to Raspberry Pi configuration menu.

Step 2: Now from the configuration menu, choose the “Localisation options”.

Step 3: Then pick the “Timezone” option.

Step 4: Now, you have to choose a Geographic Area you are currently living. In my case, its America.

Step 5: Finally, choose your city or region from the “Time Zone” section.

This will set up the time and date and it will display on your Raspberry Pi terminal.

Step 6: You can also verify the date and time by executing the below-mentioned command:

Method 2: Set Up Time and Date on Raspberry Pi Using Date Terminal

There is a terminal command too that allows you to set up the date and time manually. With this method, you can set the date and time on your Raspberry Pi system from the following command:

From the above command, you have to set the date and time by yourself and then execute this command to update the time and date on your Raspberry Pi system. -s flag is used to set the date. For example:

That’s it for this guide!

Conclusion

Setting a date and time is not a hectic task on Raspberry Pi. Generally, when a user starts the system date and time is set automatically. But still, if any problem arises and a user wants to change the date and time, then they can correct it by opening the Raspberry Pi configuration using “raspi-config” command to set up date and time on Raspberry Pi system.

About the author

Zahra Zamir

An Electronics graduate who loves to learn and share the knowledge, my passion for my field has helped me grasp complex electronics concepts and now I am here to share them with others.

How to Set the Date & Time on Raspberry Pi (Desktop & Lite)

In most cases, the Raspberry Pi operating system will set the date and time automatically, and it shouldn’t be an issue. But in some cases, like if you are just getting started on Raspberry Pi or don’t have an Internet connection, it can be an issue. In this post, we’ll learn how to set the date & time on Raspberry Pi.

NTP is enabled by default on Raspberry Pi OS and will connect to an Internet server to set the date and time accordingly. It’s also possible to set the date and time manually, from the desktop interface or with the command “sudo date -s ‘YYYY-MM-DD HH:MM:SS’.

I will now guide you through the details and give you a solution that should help in most cases, whether you are using a Desktop environment or not, or if your Pi is connected to the Internet or not.

If you are looking to quickly progress on Raspberry Pi, you can check out my e-book here. It’s a 30-day challenge, where you learn one new thing every day until you become a Raspberry Pi expert. The first third of the book teaches you the basics, but the following chapters include projects you can try on your own.

Why are date and time an issue on Raspberry Pi?

On a computer, you’ll rarely think about setting the date and time correctly. You might configure it after the installation and then forget about it for years. But on Raspberry Pi, you might have an issue, especially when using it without the Internet, or not using a recent Raspberry Pi OS version.

The first reason is that Raspberry Pi OS relies on an Internet connection to get and keep the correct date and time.

On the desktop version, there are no ways to set the date and time directly in the Interface, the only thing you can change is the time zone.

But the other reason comes from hardware specificity.
On any computer, there is a battery that allows the computer to “remember” the date and time, even when disconnected from a power source for a long time. On Raspberry Pi, there isn’t such a thing.

Lithium battery on a computer motherboard

On recent Raspberry Pi OS versions (since Stretch I think), a package is included to fix this: “fake-hwclock”. It will store the current date and time in the operating system files, to restore it after a reboot if there is no Internet connection.

If you are using an older Raspberry Pi OS system, or a different operating system, it might be something to look at before going further, as I will not cover this case in the following.

Note: If you need a hardware clock, there is a way to add a module (like this one on Amazon) via the GPIO pins. I won’t explain this in detail here, but that’s something to think about for projects where time is important but where the Raspberry Pi is not connected to the Internet.

Setting Date and Time on Raspberry Pi OS with Desktop

If you are on Raspberry Pis OS, the date and time configuration should be pretty easy if you have Internet access. But let’s take a look at what you can do to set it correctly.

Use the welcome wizard

On the first boot on Raspberry Pi OS, a configuration wizard will show up and ask you for a bunch of information, including your location. Your Pi doesn’t ask for it out of curiosity, but to set the time zone according to your answer.

Once the timezone is set, the operating system will synchronize the system date and time with an Internet server, and display the correct clock depending on your location. In most cases, you’ll be set after that. The Raspberry Pi will synchronize regularly with a time provider, and it should be ok.

I have a complete guide on how to set up Raspberry Pi OS here, if you need a more in-depth step-by-step explanation.

Use the Raspberry Pi configuration tool

If you miss the welcome wizard or need to change something in your current configuration, you can use the Raspberry Pi configuration tool on your system.

In the main menu, go to Preferences > Raspberry Pi Configuration.
In the “Localisation” tab, you can change the current time zone:

Choose the one corresponding to your location, and click on “Ok” twice to save the changes.
A few seconds later, the time should be updated in the top-right corner.

On Raspberry Pi OS with a Desktop, this is the only control you have directly in the interface. You can set a different time zone, but can’t set the date and time manually. To manage this, you need to use the command line.

So, if these tips didn’t help you, keep reading to find other solutions.

If you are a bit lost on Raspberry Pi OS Desktop and need help getting started, I have a solution for you. My Raspberry Pi Bootcamp course will guide you through the first steps, from understanding the hardware to setting up your first OS as a Desktop replacement. You can find more details about it on this page.

Setting the Date and Time in the Command Line

If you are using Raspberry Pi OS Lite or are connected via SSH, you don’t have access to these tools. Not to worry, there are similar alternatives while in the command line.

Use Raspi-config

The easiest way to fix your time zone is to use raspi-config, to get similar results quickly.
Raspi-config is the main configuration tool available on Raspberry Pi OS Lite, allowing you to configure many things, including date and time:

  • Start the tool with this command:
    sudo raspi-config
  • Got to “Localisation options”, then “Timezone”:
  • Pick a geographic area and a specific time zone:

Once done, the system configuration will be updated with the new date/time.

By the way, you can use this command to display the current date and time:
date

In one command

So, Raspi-config will help us to do the same thing as in the Desktop interface, but can’t still configure the date and time manually. The only way to set a custom date is to use the command line.

Here is the command to set the date and time manually:
sudo date -s ‘DATE’
For example:
sudo date -s ‘2021-01-04 13:04:00’
The date is not required, you can also use:
sudo date -s ’13:04:00′
It works the same way.

The date command will handle most date formats, but you can find more information on the GNU website here if you have any doubts.
Use the command “date” to check if it changed as expected:
date

This command is pretty common on all Linux distributions (link to my favorites), so it should work even if you are not using Raspberry Pi OS.

However, it might not work if your system has time synchronization enabled (NTP). You need to disable it first with:
sudo timedatectl set-ntp false
Once disabled, do the previous command again, and it should keep your entry as the current date/time.

And to switch back to automatic date, just enable NTP again with:
sudo timedatectl set-ntp true

Are you a bit lost in the Linux command line? Check this article first, for the most important commands to remember, and a free downloadable cheat sheet so you can have the commands at your fingertips.

NTP and Timedatectl configuration

By the way, NTP and Timedatectl are the tools you might need to understand if you want to go a bit further on this topic. They are the reason why the time and date synchronization is working with an Internet connection, but not so well without it.

NTP is the protocol used for time synchronization on a network, and timedatectl is the tool installed by default on Raspberry Pi OS to manage it.
For example, even if your Raspberry Pi doesn’t have Internet access, but can access a local network with a time server, you can edit the configuration to synchronize it with your own server instead of a “random” Internet server.

I will not go into more detail about this, but I have a dedicated guide about NTP that you should definitely read if you are interested.

If you are looking for exclusive tutorials, I post a new course each month, available for premium members only. Join the community to get access to all of them right now!

Video

If you want to see those tips in action, you can watch this video on my YouTube channel:

Once your initial system setup done, you are ready to move to the next steps, here are a few suggestions:

Additional Resources

Not sure where to start?
Understand everything about the Raspberry Pi, stop searching for help all the time, and finally enjoy completing your projects.
Watch the Raspberry Pi Bootcamp course now.

Master your Raspberry Pi in 30 days
Don’t want the basic stuff only? If you are looking for the best tips to become an expert on Raspberry Pi, this book is for you. Learn useful Linux skills and practice multiple projects with step-by-step guides.
Download the e-book.

VIP Community
If you just want to hang out with me and other Raspberry Pi fans, you can also join the community. I share exclusive tutorials and behind-the-scenes content there. Premium members can also visit the website without ads.
More details here.

Need help building something with Python?
Create, understand and improve any Python script for your Raspberry Pi.
Learn the essentials, step-by-step, without losing time understanding useless concepts.
Get the e-book now.

You can also find all my recommendations for tools and hardware on this page.

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

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