Javascript or Python - How do I figure out if it's night or day?

前端 未结 3 787
感情败类
感情败类 2021-02-05 05:54

any idea how I figure out if it\'s currently night/day or sunrise/dawn based on time and location of the user?

I haven\'t found anything useful that I c

3条回答
  •  半阙折子戏
    2021-02-05 06:41

    PyEphem can be used to calculate the time to the next sunrise and sunset. Building upon a blog post I found and the documentation of rise-set, your problem can be solved as follows. Lets assume I am your user, and my location is Oldenburg (Oldb), Germany.

    import ephem
    
    user = ephem.Observer()
    user.lat = '53.143889'    # See wikipedia.org/Oldenburg
    user.lon = '8.213889'     # See wikipedia.org/Oldenburg
    user.elevation = 4        # See wikipedia.org/Oldenburg
    user.temp = 20            # current air temperature gathered manually
    user.pressure = 1019.5    # current air pressure gathered manually
    
    next_sunrise_datetime = user.next_rising(ephem.Sun()).datetime()
    next_sunset_datetime = user.next_setting(ephem.Sun()).datetime()
    
    # If it is daytime, we will see a sunset sooner than a sunrise.
    it_is_day = next_sunset_datetime < next_sunrise_datetime
    print("It's day." if it_is_day else "It's night.")
    
    # If it is nighttime, we will see a sunrise sooner than a sunset.
    it_is_night = next_sunrise_datetime < next_sunset_datetime
    print("It's night." if it_is_night else "It's day.")
    

    Notes

    • For some reason lat and lon need to be strings but ephem does not complain if they are floats.
    • For best results, you might want to get the current air temperature and air pressure.

    Prerequisites

    This should work with at least Python 2.7 (with pip-2.7 install pyephem) and Python 3.2 (with pip-3.2 install ephem).

    Make sure to have a network time protocol client running on the system. E.g. on Debian Linux:

    $ sudo apt-get install ntp
    $ sudo /etc/init.d/ntp start
    

    Make sure to have the correct timezone set on your system. E.g. on Debian Linux:

    $ sudo dpkg-reconfigure tzdata
    

提交回复
热议问题