Python 如何在线获取日期?

13 投票
9 回答
17777 浏览
提问于 2025-04-15 11:49

我想知道怎么用Python在线获取当前的日期、月份和年份。我的意思是,不是从电脑的日期获取,而是访问一个网站来获取,这样就不依赖于电脑的时间。

9 个回答

5

可以使用这个NTP服务器。

import ntplib
import datetime, time
print('Make sure you have an internet connection.')

try:

    client = ntplib.NTPClient()
    response = client.request('pool.ntp.org')
    Internet_date_and_time = datetime.datetime.fromtimestamp(response.tx_time)  
    print('\n')
    print('Internet date and time as reported by NTP server: ',Internet_date_and_time)


except OSError:

    print('\n')
    print('Internet date and time could not be reported by server.')
    print('There is not internet connection.')
    
5

如果你不能使用NTP(网络时间协议),而是想用HTTP来获取时间,你可以用这个代码:urllib.urlget("http://developer.yahooapis.com/TimeService/V1/getTime"),然后解析返回的结果:

<?xml version="1.0" encoding="UTF-8"?>
<Error xmlns="urn:yahoo:api">
        The following errors were detected:
        <Message>Appid missing or other error </Message>
</Error>
<!-- p6.ydn.sp1.yahoo.com uncompressed/chunked Mon May 25 18:42:11 PDT 2009 -->

注意,返回的时间(是太平洋夏令时间,PDT)在最后的评论里(错误信息是因为缺少APP ID)。可能还有其他更合适的网络服务可以用HTTP获取当前的日期和时间(不需要注册等),因为比如在Google App Engine上提供这样的服务是非常简单的,但我目前想不起来有哪个服务。

40

考虑到“这应该是非常简单的”这一点,我就自己做了一个谷歌应用引擎的网页应用。当你访问这个网站时,它会返回一个简单的响应,声称是HTML格式,但实际上只是一个字符串,比如 2009-05-26 02:01:12 UTC\n。你有什么功能需求吗?-)

下面是使用Python的urllib模块的示例:

Python 2.7

>>> from urllib2 import urlopen
>>> res = urlopen('http://just-the-time.appspot.com/')
>>> time_str = res.read().strip()
>>> time_str
'2017-07-28 04:55:48'

Python 3.x+

>>> from urllib.request import urlopen
>>> res = urlopen('http://just-the-time.appspot.com/')
>>> result = res.read().strip()
>>> result
b'2017-07-28 04:53:46'
>>> result_str = result.decode('utf-8')
>>> result_str
'2017-07-28 04:53:46'

撰写回答