Python使用免费天气API,获取全球任意地区的天气情况

需求背景:

公司是做外贸服装的,在亚马逊平台上有多个地区店铺运营,运营人员需要参考地区的天气情况,上新的服装.所以需要能够获取全球任意地区的天气情况.还需要预测未来10-15天的天气情况.

选型API:

天气API中有大把免费的api,如:国内的心知天气,国际的雅虎,还有今天的主角:wunderground

最终选择了wunderground,原因:1,需求是全球任意地区的(国内API请求国外地区需要收费才能访问), 2.wunderground提供是信息最全,最丰富的天气api.雅虎提供的天气API信息非常之简略.


直入主题:

官方API文档

这里的免费api只是说测试账号每天有500次的免费请求,要是公司需求大的话,那么就需要付费了.官网价格

准备工作,你需要在官网注册一个账号,然后随意打开一个API的文档, 你会见到

http://api.wunderground.com/api/Your_Key/conditions/q/CA/San_Francisco.json

当中Your_Key的位置有一串key.请保管记住.


python代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 18年3月6日 下午1:53
# @Author  : dongyouyuan
# @email   : 15099977712@163.com
# @File    : weatherApi.py
# @Software: PyCharm
#
# 通过全球天气预报API:http://api.wunderground.com(信息最多最全) 来获取信息

import requests
import json
import datetime
import time
import operator


def timeStamp_to_dataTime(timestamp, format='%Y-%m-%d'):
    """
    时间戳转换成格式化的时间
    :param timestamp: 时间戳
    :param format: 格式
    :return:
    """
    if timestamp is None or not timestamp:
            return ''
    return datetime.datetime.fromtimestamp(int(timestamp)).strftime(format)


def dataTime_to_timeStamp(data_tiem, format='%Y-%m-%d %H:%M'):
    """
    格式化时间格式转换成时间戳
    :param data_tiem: 格式化时间
    :param format: 格式
    :return:
    """
    if not data_tiem:
        return 0
    else:
        try:
            time_array = time.strptime(data_tiem, format)
            time_stamp = int(time.mktime(time_array))
            return time_stamp
        except Exception as error_msg:
            print(error_msg)
            return 0


def get_recent_10_days(date):
    """
    获取前10天的时间格式 20180306
    :return: 返回列表
    """

    date_list = list()
    for i in range(1, 11):
        tmp_date = (datetime.datetime.strptime(date, "%Y%m%d") - datetime.timedelta(days=i)).strftime('%Y%m%d')
        date_list.append(tmp_date)
    return date_list


def sorted_for_list_dict(list_dict, key, reverse=False):
    """
    为列表排序,按照元素中dict的key
    :param list_dict:
    :param key:
    :return:
    """
    return sorted(list_dict, key=operator.itemgetter(key), reverse=reverse)


class Weather(object):
    def __init__(self):
        self.search_url = 'http://autocomplete.wunderground.com/aq'
        self._url =
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值