pythondatetimetimepytz

Get datetime of specified timezone irrespective of datetime set in computer


I want to print the datetime of timezone "Asia/Kathmandu". I have used the below code:

import datetime, pytz

tz = pytz.timezone("Asia/Kathmandu")
ktm_now = datetime.datetime.now(tz)
print(ktm_now)

The problem is that it gave me the datetime that is set in my computer instead of datetime of "Asia/Kathmandu". Right now the datetime of "Asia/Kathmandu" should be 19:55:00 but I have manually changed the time of my computer to 21:30:00. And after doing this, as soon as I run the above code, it surprisingly gives me datetime which is of my computer (21:30:00) instead of 19:55:00. What can be the reason? How to get the datetime of a specified timezone like "Asia/Kathmandu" instead of datetime set in computer?


Solution

  • Here's a way how to get the time from an independent source (assuming you have internet access):

    import datetime
    import ntplib # pip install ntplib
    import dateutil # Python 3.9: use zoneinfo
    
    tz_info = dateutil.tz.gettz("Asia/Kathmandu")
    
    ntp_server = 'pool.ntp.org'
    c = ntplib.NTPClient()
    
    response = c.request(ntp_server)
    dt = datetime.datetime.fromtimestamp(response.tx_time, tz=tz_info)
    # response.tx_time holds NTP server timestamp in seconds since the epoch / Unix time
    # note that using response.tx_time here ignores network delay
    
    print(dt)
    # 2021-03-06 21:13:20.112861+05:45
    
    print(repr(dt))
    # datetime.datetime(2021, 3, 6, 21, 13, 20, 112861, tzinfo=tzfile('/usr/share/zoneinfo/Asia/Kathmandu'))
    
    print(dt.utcoffset())
    # 5:45:00
    

    package: ntplib, background info: Network Time Protocol