Amila Pathum Kandambi
Amila Pathum Kandambi

Reputation: 53

NTPLib Time Difference + Python

while using ntp time, (UK) it always returns one hour less than the actual time. Eg: now time is 13.35 But when I say date, it returns 12.35. Any suggestions ?

    try:
        c = ntplib.NTPClient()
        response = c.request('uk.pool.ntp.org', version=3)
    except:
        print "Error At Time Sync: Let Me Check!"

Upvotes: 1

Views: 2036

Answers (1)

Amila Pathum Kandambi
Amila Pathum Kandambi

Reputation: 53

Finally, I could figure out the answer and If some one is looking for the answer, UTC time differs from British Summer Time (BST) [Have to + or - Some hours accordingly] Here in python, there is a library called pytz and this library allows accurate and cross platform timezone calculations using Python 2.4 or higher . Here is how my coding looks like. Hope this will help someone. Thanks!!

#!/usr/bin

import pytz
import datetime
import ntplib
import time

LOCALTIMEZONE = pytz.timezone("Europe/London") # time zone name from Olson database

def utc_to_local(utc_dt):
    return utc_dt.replace(tzinfo=pytz.utc).astimezone(LOCALTIMEZONE)

def get_time_from_NTPClient():
    from time import ctime
    try:
        c = ntplib.NTPClient()
        response = c.request('europe.pool.ntp.org', version=3)
        formatted_date_with_micro_seconds =    datetime.datetime.strptime(str(datetime.datetime.utcfromtimestamp(response.tx_time)),"%Y-%m-%d %H:%M:%S.%f")
        local_dt = utc_to_local(formatted_date_with_micro_seconds)
        #Remove micro seconds from the string
        formatted_date_with_corrections = str(local_dt).split(".")[0]
        return formatted_date_with_corrections
    except:
        print "Error At Time Sync: Let Me Check!"
        return "Error At Time Sync: Let Me Check!" 

formatted_date = get_time_from_NTPClient()

Upvotes: 2

Related Questions