139

WSL2 clock goes out of sync after resuming from sleep/hibernate. illustration showing Windows clock and WSL clock out of sync

A workaround was shared on GitHub sudo hwclock -s to resync clock in WSL, but you have to do this every time you resume from sleep/hibernate.

piouson
  • 3,328
  • 3
  • 29
  • 29

16 Answers16

179

In case anyone finds this via search and doesn't notice that there is actually a solution listed in the question, you can fix WSL clock drift via.

sudo hwclock -s

If you just need to do it occasionally, this is a fine solution. If you need to do it more frequently, consider @piouson's solution

Don Alvarez
  • 2,017
  • 2
  • 12
  • 12
  • 1
    I was hoping this would also work on WSL 1, but I got error `hwclock: Cannot access the Hardware Clock via any known method.`. – Ryan May 19 '21 at 19:45
  • **Also note this bug is fixed, you just need to install the kernel update** - see the other answer. – mikemaccana Apr 07 '22 at 08:37
  • 6
    Still (or again) seeing drift with Kernel 5.15.79.1-microsoft-standard-WSL2 (WSL date was in the future). – leopold.talirz Jan 03 '23 at 12:06
  • 2
    Occasionally also the hardware clock shows wrong time, so this does not help and you need to use something like ntpdate. The problem fixed at some point, but it resurfaced. There's an issue for this in the WSL GitHub: https://github.com/microsoft/WSL/issues/10006 – Juha Palomäki Jun 01 '23 at 13:10
  • 2
    I'm still having this problem, but `hwclock` didn't help. `sudo ntpdate ntp.ubuntu.com` worked for me. – crockeea Jul 27 '23 at 23:53
52

Update

The fix is now in WSL2 Linux kernel 5.10.16.3 and newer! Note you may need to install WSL2 from the Windows Store to get the latest kernel version per this thread with Craig from Microsoft.

Older Answer

sudo hwclock -s gets you kind of there, but for some reason doesn't get the exact time - I often find it's a minute or so in the future!

sudo ntpdate pool.ntp.org should get you the correct time.

But this is all because of a bug in the Linux kernel which should be included in a Windows update at some point...

There are a number of hacks referenced in the the GitHub issue which can work around this, mostly, but not always, in my experience...

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
drkvogel
  • 2,061
  • 24
  • 17
  • 4
    I was debugging my script for 2 days before realizing it was a clock issue. hwclock -s didn't work for me. ntpdate did. thank you!!!!! – Peppershaker Apr 16 '21 at 19:11
  • 2
    I have 5.10.102.1-microsoft-standard-WSL2 installed and I have to do this every time. Am I missing someting? – Micah Smith Oct 21 '22 at 22:23
  • Please note that you can check your WSL version using `wsl --status`. In my case, I was on an outdated version, and in contrast to my expectations, it was not updated by Windows update regularly, as I had unticked "Receive updates for other Microsoft products" in the Windows update settings in the past. Ticking that box let Windows Update update my WSL and fix the issue. – jvz Dec 25 '22 at 11:38
  • ntp is the ultimate tool, hwclock is not working for me. – ospider Jan 31 '23 at 13:23
  • 15
    I'm using kernel 5.15.79.1-microsoft-standard-WSL2 and it's still affected when I suspend my laptop. – Paulo Freitas Feb 12 '23 at 16:45
  • 6
    Same here, I am on `5.15.79.1-microsoft-standard-WSL2`, and I still have this problem. `wsl --status` shows `Default Distribution: Ubuntu-22.04` `Default Version: 2` – user1507435 Feb 14 '23 at 14:54
  • I've been running into this a lot the last couple of months, but I did not experience it last year. I'm running 5.15.90.1. – bfuzze Mar 15 '23 at 14:17
  • 8
    That kernel update definitely didn't fix the issue, I'm also still having the issue on the latest insider build of WSL – Tofandel Mar 27 '23 at 09:52
  • 1
    It is known, that the fix mentioned in the given answer did not fix the issue for all https://github.com/microsoft/WSL/issues/5324#issuecomment-1481953716. – Stefan Bollmann Mar 29 '23 at 10:23
  • Had this today on 5.15.90.1 after months of no issues, but @PauloFreitas's comment pointed me to the cause, which was that I had put my laptop to sleep! I never do that... but did it last night. Thanks Paulo! :) – Peter Hansen Aug 30 '23 at 01:44
39

Just restart wsl, it works fine for me

wsl --shutdown

then

wsl

in PowerShell

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
fahmiduldul
  • 924
  • 7
  • 18
  • 4
    but you have to restart every time the issue recurs..? – piouson Feb 15 '21 at 10:44
  • @piouson exactly – fahmiduldul Feb 15 '21 at 13:40
  • 2
    my solution removes the need to restart each time, by using Windows Task Scheduler for auto re-run.. – piouson Feb 15 '21 at 15:13
  • 2
    I give options to anyone too lazy to do your solution. It's up to them to choose which one – fahmiduldul Mar 07 '21 at 05:32
  • 3
    I was trying to change my WSL and Windows date to something in the future to do some tests and this is what worked for me. What people are answering wrong is that `sudo hwclock -s` will sync to Windows, but it's wrong. It actually syncs the date to your hardware clock. Restarting WSL (which is what this answer suggests) syncs to windows, so you can change both Windows and WSL to some fake date easily. Thanks :) – Float07 Dec 02 '21 at 11:44
  • 2
    the simplest and effective solution if you are not actually executing anything in WSL. thanks! – logoff Jul 09 '22 at 16:07
  • Works for me. I was having issues with sessions on a dockerized ASP Core app due to date info that made them expire earlier. – Carlos Mar 25 '23 at 21:38
  • This is the most idomatic solution for Windows users: turning it off and on again. – Damien Aug 16 '23 at 14:31
26

UPDATE: as mentioned by drkvogel, the Clock Sync fix was released in WSL2 kernel version 5.10.16.3, however, you should install the Windows Store version of WSL:

# powershell install by id
winget install 9P9TQF7MRM4R

# powershell install by name
winget install 'Windows Subsystem for Linux'

At time of writing, this GitHub Issue was open for the bug.

The workaround I chose for my situation (single distro in WSL2) is to use Windows Task Scheduler to run hwclock in WSL whenever Windows resyncs hardware clock.

Windows: Open PowerShell as Administrator

schtasks /create /tn WSLClockSync /tr "wsl.exe sudo hwclock -s" /sc onevent /ec system /mo "*[System[Provider[@Name='Microsoft-Windows-Kernel-General'] and (EventID=1)]]"
Set-ScheduledTask WSLClockSync -Settings (New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries)

WSL2: Run sudo visudo and add hwclock to sudoers to skip password prompt

# bottom of my file looks like this
...
...
#includedir /etc/sudoers.d
<username> ALL=(ALL) NOPASSWD:/usr/sbin/hwclock, /usr/bin/apt update, /usr/bin/apt upgrade

Results

illustration showing Windows clock and WSL clock in sync

See image for how to get Event XPath from Windows Event filtering. Use as provided to let task scheduler auto-display scheduled triggers.

illustration showing scheduled task created

piouson
  • 3,328
  • 3
  • 29
  • 29
  • 1
    If you're running ubuntu, which is common with WSL, this approach will fail silently because the path listed for hwclock is incorrect. On ubuntu the correct path is `/sbin/hwclock` – Don Alvarez Apr 03 '21 at 12:01
  • hwclock command didn't work, had to restart WSL. I think it happened due to laptop loosing it's RTC time completely due to running out of juice. – tyger Jan 04 '22 at 14:37
  • How do you update WSL? – Oleg Yablokov Jul 13 '22 at 11:46
  • @OlegYablokov just check for updates on Windows, see [clock sync fix](https://devblogs.microsoft.com/commandline/servicing-the-windows-subsystem-for-linux-wsl-2-linux-kernel/#bug-fix-clock-sync) – piouson Jul 13 '22 at 14:37
  • I'm having this issue on kernel version `5.10.102.1-microsoft-standard-WSL2`. – fepegar Oct 07 '22 at 08:27
  • 1
    Can confirm what @fepegar said. Found this post because my clock was out of sync on `5.10.102.1-microsoft-standard-WSL2` as well. The command `sudo hwclock -s` worked though (Ubuntu 20.04) – M. Eriksson Oct 08 '22 at 23:05
  • The answer is not obsolete. This issue is still happening on `5.15.90.1` for me. – Leônidas Villeneuve Mar 28 '23 at 02:22
8

Necro'ing this: As of May 2022, this issue persists to a degree.

There are two components.

First, Windows time sync needs to be decent to start with. It's not, out of the box, on machines that aren't domain-joined.

  • Change w32time to start automatically. In Administrator cmd, but not PowerShell, sc triggerinfo w32time start/networkon stop/networkoff. Verify with sc qtriggerinfo w32time. To get into cmd that way, you can start Admin PowerShell and then just type cmd.

  • Make a few changes in regedit.

    • In Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\w32time\Config, set MaxPollInterval to hex c, decimal 12.
    • Check Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\w32time\Parameters\NtpServer. If it ends in 0x9 you are done. If it ends in 0x1 you need to adjust SpecialPollInterval in Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\w32time\TimeProviders\NtpClient to read 3600
  • Reboot, then from Powershell run w32tm /query /status /verbose to verify that w32time service did start. If it didn't, check triggers again. If all else fails, set it to Automatic Delayed startup

Second, WSL2 needs to actually stay in sync. MS will likely release another kernel fix. In the meantime a scheduled task can bring it back into sync periodically: schtasks /Create /TN WSL2TimeSync /TR "wsl -u root hwclock -s" /SC ONEVENT /EC System /MO "*[System[Provider[@Name='Microsoft-Windows-Kernel-Power'] and (EventID=107 or EventID=507) or Provider[@Name='Microsoft-Windows-Kernel-General'] and (EventID=1)]]" /F

  • 1
    I should note that for me, `hwclock -s` did not solve this issue, even though I'm running a recent WSL kernel. My Windows time is fine, but the sync... doesn't, leaving my WSL time more than 30 seconds out of date. I have to rely on `ntpdate` instead, since I am calling APIs with _very_ sensitive time requirements (5 seconds...) – Mike Caron Jun 07 '22 at 22:03
  • Did you raise a github issue for the time sync still failing after the update is installed? If you think the problem still exists someone from Microsoft will actually look at it. – mikemaccana Oct 12 '22 at 13:59
6

Use cron to schedule sudo hwclock -s

As others said before sudo hwclock -s syncs the clock,
but you will need to do this after every sleep/hibernate. Solution is to add an hourly cron task to sync the clock.

Open crontab with sudo (must open with sudo since the command uses sudo):

sudo crontab -e 

and add this code with a new line after the task (it's a cron requirement):

PATH=/sbin:/bin:/usr/bin
@hourly hwclock -s

You must either set PATH since root-cron do not has it or use absolute paths e.g. /usr/sbin/hwclock.

cron troubleshooting:

  • To verify cron is working you may add a dummy task (don't forget to add a new line):
    * * * * * date > /tmp/log.txt
  • If no file is created, verify cron is working: pgrep cron.
    If no PID shows, start cron with: sudo service cron start.
  • To learn cron timing method: cron timing generator
Nathan
  • 136
  • 2
  • 4
4

This GitHub Issue was closed

You can also run the below command in Powershell Terminal so sync it.

wsl.exe sudo hwclock -s

  • For me, this worked well. I updated my Windows 11 yesterday to the newer version and noticed the Ubuntu clock had broken since that moment. The command above solved the issue. – Laerion Oct 07 '22 at 16:54
  • Thank you so much, it solved my issue. had issues developing the Python app on WSL2 because of unsynchronized time. – Ali Abdi Feb 05 '23 at 19:52
2

You can manually update the WSL2 kernel to 5.10.16 by following the method in this comment: #5650 (comment). I have fixed the issue by this method.

Ethan
  • 21
  • 4
  • 1
    I followed the instruction and installed the latest kernal Windows Subsystem for Linux Update - 5.10.102.2. But saddly, I find the problem is still there and my wsl2 system is till few seconds ahead of the my host Windows system one day after a syncing. – yang Jun 05 '22 at 02:27
2

I've added this to Windows Task Scheduler, set to run every 12 hours:

wsl.exe -d ubuntu -u root -- ntpdate time.windows.com

To install ntpdate:

sudo apt install ntpdate

J. Scott Elblein
  • 4,013
  • 15
  • 58
  • 94
2

If that issue still happened on a version higher than 5.10.16.3 (as it was for my version 5.15.90.1) you could fix it by systemd service

Thirst, make sure that you have systemd enabled, /etc/wsl.conf has:

[boot]
systemd=true

Then install systemd-timesyncd:

sudo apt install systemd-timesyncd

Edit timesyncd config:

sudo systemctl edit systemd-timesyncd

with(to make it run inside virtualized environment):

[Unit]
ConditionVirtualization=

And start it:

sudo systemctl start systemd-timesyncd

Thanks for the solution from the github issue

Igor Alex
  • 841
  • 2
  • 10
  • 21
1

I started having this issue about 6-9 months ago. Restarting wsl always works, but that is not ideal for obvious reasons. hwclock -s running through a cron job at regular intervals worked for a few months, but not anymore. @igor-alex's approach is working for me, but it required some different steps:

/etc/wsl.conf (same as above)

[boot]
systemd=true

Install systemd-timesync (same as above)

sudo apt install systemd-timesyncd

The suggested edits for timesyncd did NOT work for me and resulted in failure to start the service. Instead I did the following:

sudo systemctl edit systemd-timesyncd.service
[Unit]
ConditionVirtualization=
ConditionVirtualization=wsl

Courtesy of https://unix.stackexchange.com/a/737366/547670

And start it (same as above)

sudo systemctl start systemd-timesyncd

HTH

bfuzze
  • 438
  • 8
  • 15
0

For me this issue seems to be happening when the system goes to sleep. So I have registered a bash command to call whenever, it goes out of sync. I did it by adding a function.sh file and sourced it in ~/.bashrc.

function.sh:

YELLOW='\033[0;33m'
NC='\033[0m'

TIME_SERVER=ntp.ubuntu.com

# Sync wsl time
sync_date () {
    echo -e "${RED}sudo ntpdate $TIME_SERVER ${NC}"
    echo
    sudo ntpdate $TIME_SERVER
}

~/.bashrc:

source ~/Linux/funtions.sh

Note that I have added a bit of color and some customizations (TIME_SERVER: [windows time server is other option]).

You can sync the time using sync_date command in cli.

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
Haribk
  • 131
  • 7
0

The problem persisted for me and hwclock/ntpd weren't quite working for my use case so I wrote a little daemon to work around the problem:

https://github.com/matthewnourse/polite-hwclock-hctosys

...I hope you find it helpful.

mafyew
  • 63
  • 1
  • 5
0

If you want to go the route of adding something to the end of your ~/.bashrc or ~/.profile, but find it annoying to have to type in your su password all the time, you can create a timed prompt to only run the update when you want. Here I have achieved this by put a wrapper around Haribk's function:

YELLOW='\033[0;33m'
NC='\033[0m'
TIME_SERVER=ntp.ubuntu.com

# Sync wsl time
sync_date () {
    # Uncomment one of the options below.
    cmd="ntpdate $TIME_SERVER"
    #cmd=hwclock -sv
    echo -e "${YELLOW}sudo ${cmd}${NC}"
    echo
    sudo $cmd
}

date
t=10
resp=
while [[ $t != 0 ]]
do
  t=$(( $t - 1 ))
  read -t1 -ep"($t) Sync clock with host? [yN] " -n1 resp
  if [[ $? == 0  && $resp == '' || ${resp,,} == 'n' ]]
  then
    break
  fi
  if [[ ${resp,,} == 'y' ]]
  then
    sync_date
    break
  fi
done
if [[ $resp == '' ]]; then echo; fi

This gives a “y/n” prompt that counts down from 9, and assumes “n” if nothing is entered in that time or the Enter key is pressed.

0

On arch linux the "sudo hwclock -s" has stopped working for me (anyone know why?)

The fix "sudo ntpdate time.windows.com" does work for me

-1

This worked for me on Ubuntu 22.04.2 LTS.

Install ntpdate

sudo apt install ntpdate

Add this line to ~/.profile

sudo ntpdate time.windows.com

Now everytime you open a new session, the date and time get synced. Also if you want to sync for an existing session, run the command :

sudo ntpdate time.windows.com