英文:
Python time of remote web server
问题
在Python中,我正在尝试获取远程服务器的精确时间,以便可以调整请求的时间。
我知道我可以使用以下代码获取"NTP"时间:
client = ntplib.NTPClient()
response = client.request('pool.ntp.org')
print(f"request packet sent LOCAL Client time: {datetime.fromtimestamp(response.orig_time, timezone.utc)}")
print(f"request packet received REMOTE Server time: {datetime.fromtimestamp(response.recv_time, timezone.utc)}")
这将返回非常有用的信息,显示我的服务器比NTP服务器快了近2秒:
request packet sent LOCAL Client time: 2023-02-17
18:14:46.008366+00:00request packet received REMOTE Server time: 2023-02-17
18:14:44.369423+00:00
是否有一种方法可以获取Web服务器的时间,而不是NTP服务器的时间?
英文:
In Python, I am trying to get the exact time of a remote server so that I can adjust the timing of a request.
I know that I can use this code to get a "ntp" time:
client = ntplib.NTPClient()
response = client.request('pool.ntp.org')
print( f"request packet sent LOCAL Client time: {datetime.fromtimestamp(response.orig_time, timezone.utc)}")
print( f"request packet received REMOTE Server time: {datetime.fromtimestamp(response.recv_time, timezone.utc)}")
Which returns very helpful information showing that my server is nearly 2 seconds ahead of the NTP server:
> request packet sent LOCAL Client time: 2023-02-17
> 18:14:46.008366+00:00
>
> request packet received REMOTE Server time: 2023-02-17
> 18:14:44.369423+00:00
Is there a way to get the time of a web server, rather than an NTP server?
答案1
得分: 1
有没有办法获取Web服务器的时间,而不是NTP服务器的时间?
在大多数情况下,您应该能够在响应头中找到 Date
,考虑以下简单示例
import requests # 如果没有安装它,可以通过 pip install requests 进行安装
r = requests.head("http://www.example.com") # 仅请求头部信息
date_str = r.headers["Date"] # 检索Date值
print(date_str) # 例如:Fri, 17 Feb 2023 18:43:06 GMT
如果您需要解析日期字符串,您可以使用 email.utils.parsedate
(标准库的一部分)。
英文:
> Is there a way to get the time of a web server, rather than an NTP
> server?
In most case you should be able to find Date
in response headers, consider following simple example
import requests # if you do not have it, install it: pip install requests
r = requests.head("http://www.example.com") # ask just for headers
date_str = r.headers["Date"] # retrieve Date value
print(date_str) # e.g. Fri, 17 Feb 2023 18:43:06 GMT
If you need to parse date string you might use email.utils.parsedate
(part of standard library).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论