import datetime
import json
import requests
# 调用老黄历 API 查询指定日期的宜忌
# 示例:查询 2024-10-01 的黄历信息
date_str = "2024-10-01"
url = f"https://huangli.tl654.com/api/huangli?date={date_str}"
try:
resp = requests.get(url, timeout=10)
resp.raise_for_status()
data = resp.json()
# 提取关键字段
yi = data.get("yi", []) # 宜:嫁娶、出行、开业...
ji = data.get("ji", []) # 忌:动土、安葬...
chong = data.get("chong", "") # 冲煞:冲虎(庚寅) 煞南
print(f"日期: {date_str}")
print(f"宜: {', '.join(yi)}")
print(f"忌: {', '.join(ji)}")
print(f"冲煞: {chong}")
# 吉时示例(子丑寅卯...时辰的吉凶)
good_hours = data.get("good_hours", [])
if good_hours:
print(f"吉时: {', '.join(good_hours)}")
except requests.exceptions.RequestException as e:
print(f"网络请求失败: {e}")
except json.JSONDecodeError:
print("返回数据格式异常")
# 输出示例:
# 日期: 2024-10-01
# 宜: 嫁娶, 出行, 开业, 祭祀, 祈福
# 忌: 动土, 安葬, 破土
# 冲煞: 冲虎(庚寅) 煞南
# 吉时: 寅时, 卯时, 午时
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
// 定义响应结构体
type HuangliResponse struct {
Yi []string `json:"yi"`
Ji []string `json:"ji"`
Chong string `json:"chong"`
GoodHours []string `json:"good_hours"`
}
func main() {
// 查询 2024-10-01 的黄历
date := "2024-10-01"
url := fmt.Sprintf("https://huangli.tl654.com/api/huangli?date=%s", date)
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Get(url)
if err != nil {
fmt.Printf("请求失败: %v\n", err)
return
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("读取响应失败: %v\n", err)
return
}
var data HuangliResponse
if err := json.Unmarshal(body, &data); err != nil {
fmt.Printf("JSON 解析失败: %v\n", err)
return
}
fmt.Printf("日期: %s\n", date)
fmt.Printf("宜: %v\n", data.Yi)
fmt.Printf("忌: %v\n", data.Ji)
fmt.Printf("冲煞: %s\n", data.Chong)
if len(data.GoodHours) > 0 {
fmt.Printf("吉时: %v\n", data.GoodHours)
}
}
// 输出示例:
// 日期: 2024-10-01
// 宜: [嫁娶 出行 开业 祭祀 祈福]
// 忌: [动土 安葬 破土]
// 冲煞: 冲虎(庚寅) 煞南
// 吉时: [寅时 卯时 午时]
// 浏览器端或 Node.js 调用老黄历 API
const date = '2024-10-01';
const url = `https://huangli.tl654.com/api/huangli?date=${date}`;
// 使用 fetch(浏览器原生 / Node 18+)
fetch(url)
.then(resp => {
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
return resp.json();
})
.then(data => {
console.log(`日期: ${date}`);
console.log(`宜: ${data.yi.join(', ')}`);
console.log(`忌: ${data.ji.join(', ')}`);
console.log(`冲煞: ${data.chong}`);
if (data.good_hours?.length) {
console.log(`吉时: ${data.good_hours.join(', ')}`);
}
})
.catch(err => console.error('请求失败:', err));
// 输出示例:
// 日期: 2024-10-01
// 宜: 嫁娶, 出行, 开业, 祭祀, 祈福
// 忌: 动土, 安葬, 破土
// 冲煞: 冲虎(庚寅) 煞南
// 吉时: 寅时, 卯时, 午时
// 如需兼容旧浏览器,可用 XMLHttpRequest 替代:
// const xhr = new XMLHttpRequest();
// xhr.open('GET', url, true);
// xhr.onload = () => {
// if (xhr.status === 200) {
// const data = JSON.parse(xhr.responseText);
// console.log(data);
// }
// };
// xhr.onerror = () => console.error('请求失败');
// xhr.send();