通过HTTP获取当前时间

时间:2015-11-17 16:49:54

标签: xml http time

是否有一些HTTP服务器或其他公共服务可以通过单个HTTP请求轻松获取当前时间,无论使用何种编程语言?

例如,我想浏览这样的网址:

http://www.thebesttimeserverintheworld.com/index.php?when=now

得到这样的东西:

<exactTime>
    <time>15:00:00</time>
    <timeZone>GMT +0100</timeZone>
</exactTime>

1 个答案:

答案 0 :(得分:1)

我非常有信心您可能已经解决了这个问题,但是这里有一种方法可以完成从 HTML 源而不是通过 UDP 123 的 NTP 服务器查询时间的任务。

import requests
import re as regex
from bs4 import BeautifulSoup

raw_req = requests.get('https://www.worldtimeserver.com/current_time_in_UTC.aspx')
soupParser = BeautifulSoup(raw_req.content, 'lxml')
date_time = soupParser.find('div', {'class': 'local-time'})
date_today = date_time.find('h4').get_text().strip()
current_time = date_time.find('span', {'id': 'theTime'})
epoch_time = date_time.find('input', {'id': 'serverTimeStamp'})['value']
GMT_24_hour = date_time.find_all('p')[1]

clean_str = regex.sub("\s\s+", " ", GMT_24_hour.get_text())
get_gmt_time = regex.search(r'(UTC\/GMT is)\s(\d{2}:\d{2})\s(on)', clean_str)
print(get_gmt_time.groups()[1])

print(f'Current Date: {date_today}')
print(f"Current UTC time: {current_time.get_text().strip()}")
print(f'Current GMT 24 time: {get_gmt_time.groups()[1]}')
print(f'Epoch Time: {epoch_time}')

#output
Current Date: Saturday, March 6, 2021
Current UTC time: 4:18:38 PM
Current GMT 24 time: 16:18
Epoch Time: 1615047518834.02

您也可以从 World Clock API

中提取时间
from datetime import datetime
import requests

raw_req = requests.get('http://worldclockapi.com/api/json/utc/now')
date_time_elements = raw_req.json()
current_date = date_time_elements['currentDateTime']
day_of_the_week = date_time_elements['dayOfTheWeek']
time_zone = date_time_elements['timeZoneName']
epoch_time = date_time_elements['currentFileTime']
clean_date = datetime.strptime(current_date, "%Y-%m-%dT%H:%M%z")

print(f'Current Date: {clean_date.date()}')
print(f'Current Time: {clean_date.time()}')
print(f"Day of the Week: {day_of_the_week}")
print(f'Time Zone: {time_zone}')
print(f'Epoch Time: {epoch_time}')

#output
Current Date: 2021-03-06
Current Time: 22:10:00
Day of the Week: Saturday
Time Zone: UTC
Epoch Time: 132595422573678391