2

I need to get the current UNIX epoch at UTC in Python and I've tried the following:

from datetime import datetime
from datetime import timezone
import time 
import calendar

def get_nonce():
    unix_epoch = datetime.utcfromtimestamp(0).replace(tzinfo=timezone.utc)

    now = datetime.now(tz=timezone.utc)

    seconds = (now - unix_epoch).total_seconds()

    return int(seconds)
    
def get_time():
    current_time_seconds = time.time()
    
    return int(current_time_seconds)
    
def get_time_utc():
    current_time_seconds = datetime.now(timezone.utc).timestamp() 
    
    return int(current_time_seconds)
    
def get_time_again():
    current_time = int(calendar.timegm(time.gmtime()))
    
    return int(current_time)
    
print(get_nonce())

print(get_time())

print(get_time_utc())

print(get_time_again())

All are 1 hour behind from the current epoch which I check with this website: https://www.unixtimestamp.com/

What can be the reason why? time.tzname says I'm at UTC and using date +%s on the command line also returns a value that's about an hour behind as well.

I started getting the wrong epoch value yesterday and it's been hindering my progress since the API I'm integrating with requires the current epoch value in the body

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
neil_ruaro
  • 368
  • 3
  • 15
  • 1
    If command line `date` also shows that error, then it's not Python or your code that's broken but your machine; maybe through a misbehaving time server. You might get better answers on https://superuser.com – Homer512 Jun 06 '23 at 10:40
  • It turns out my WSL suddenly got out of sync with the current time `sudo hwclock -s` fixed my issue – neil_ruaro Jun 06 '23 at 10:50

1 Answers1

1

turns out to be a persistent WSL2 issue: WSL2 Clock is out of sync with Windows Solved my issue by using sudo hwclock -s on the command line

neil_ruaro
  • 368
  • 3
  • 15