Search code examples
pythonutc

get UTC time directly from a website in python


i want to get the utc time directly from a website that can give that. and i don't want to use python modules because they give me the system time and my system time does not show the correct time. how can i get the correct utc time without changing the system time? i use

import ntplib,datetime
x = ntplib.NTPClient()
datetime.datetime.utcfromtimestamp(x.request('europe.pool.ntp.org').tx_time)

but i get this error

raise NTPException("No response received from %s." % host)
ntplib.NTPException: No response received from europe.pool.ntp.org.

Solution

  • Could you try to call datetime.utcnow()? From the python docs

    Here is my output

    >>> import datetime
    >>> datetime.datetime.utcnow()
    datetime.datetime(2018, 11, 4, 9, 47, 59, 572104)
    

    Edit as OP having issues with above

    As for a web based solution, this works fine for me (Whilst avoiding your website

    >>> import requests
    >>> x = requests.get('http://worldtimeapi.org/api/timezone/Europe/London.txt')
    >>> print(x.content)
    b'abbreviation: GMT\ndatetime: 2018-11-04T10:09:18.395273+00:00\nday_of_week: 0\nday_of_year: 308\ndst: false\ndst_from: \ndst_until: \ntimezone: Europe/London\nunixtime: 1541326158\nutc_offset: +00:00\nweek_number: 44'
    

    Update

    You can get the datetime like so. I am certain there is a better way to do this, but this method works fine for this specific use-case.

    >>> import requests
    >>> x = requests.get('http://worldtimeapi.org/api/timezone/Europe/London.txt')
    >>> y = x.text
    >>> print(y[27:47])
    2018-11-04T11:01:46