Javascript或Python - 我如何确定它是夜晚还是白天? [英] Javascript or Python - How do I figure out if it's night or day?
问题描述
任何想法如何根据用户的时间和地点确定当前是夜晚/白天还是日出/黎明?
我没有发现任何有用的东西,我可以在客户端或后端使用。
小时并不一定会定义它是否是夜晚,一天,这几乎取决于年,月,日,小时和地理坐标。
澄清...来模拟这样的事情。
一种近似的方式也是非常有用的。
希望有人能帮上忙!
您可以像我一样做,并使用此公开网域 Sun.py 模块来计算的位置太阳相对于地球上的位置。这是相当古老的,但多年来对我很好。我对它做了一些表面修改,使其更新于Python 2.7,例如使其中的少数类变为新的类,但大部分内容没有改变。
下面是我创建的一个模块,名为sunriseset.py,它显示了如何使用它来计算给定地理坐标和时区的特定位置的日出和日落时间。引用的时区
模块是 tzinfo
datetime
模块文档中描述的抽象基类在 tzinfo $ c
$ b
# - * - coding:iso-8859-1 - * -
import datetime
import timezone#基于Python文档的具体tzinfo子类
从Sun导入数学
导入Sun
__all__ = ['getsuninfo','Place' ]
$ b $ class地点(对象):
def __init __(self,name,coords,tz = timezone.Pacific):
self.name = name#string
self.coords = coords#tuple(E / W long,N / S lat)
self.tz = tz#tzinfo常数
f_hoursmins(小时):
将浮点小数时间以小时为单位转换为整数小时,分钟
frac,h = math.modf(小时)
m = round(frac * 60,0)
if m == 60:#四舍五入到下一个小时
h + = 1; m = 0
返回int(h),int(m)
$ b $ def _ymd(日期):
从datetime对象返回y,m,d作为元组
返回date.timetuple()[:3]
def getsuninfo(位置,日期=无):
返回日出,日落和本地日期时间)
if date == None:
querydate = datetime.date.today()
else:#给出的日期应该是datetime实例
querydate = date
$ b $ args = _ymd(querydate)+ location.coords
utcrise,utcset = Sun()。sunRiseSet(* args)
daylength = Sun()。dayLength (* args)
hrs,mins = _hoursmins(daylength)
risehour,risemin = _hoursmins(utcrise)
sethour,setmin = _hoursmins(utcset)
#将时间转换为timedelta值(即从午夜的utc开始)
midnight = datetime.datetime(tzinfo = timezone.utc,* _ymd(querydate))
deltarise = datetime.timedelta(小时= risehour,minutes = risemin)
utcdat etimerise = midnight + deltarise
deltaset = datetime.timedelta(hours = sethour,minutes = setmin)
utcdatetimeset = midnight + deltaset
将UTC时间结果转换为本地时间位置
localrise = utcdatetimerise.astimezone(location.tz)
localset = utcdatetimeset.astimezone(location.tz)
返回localrise,localset,hrs,mins
if __name__ ==__main__:
import datetime,timezone
unit unittest ,testdate)
printLocation:,location.name
printDate:,testdate.strftime(%a%x)
print risetime.strftime( 日出%I:%M%p),settime.strftime( - Sunset%I:%M%p(%Z))
printdaylight:%d:%02d%(hrs,分钟)
print
place = Place(My House,(-121.990278,47.204444),timezone.Pacific)
# ter DST转换
printpre 2007
print=========
unittest(place,datetime.date(2006,4,1))
unittest(place,datetime.date(2006,4,2))
unittest(place,datetime.date(2006,10,28))
unittest(place,datetime.date(2006,10 ,29))
print2007
print=========
unittest(place,datetime.date(2007,3,10) )
unittest(place,datetime.date(2007,3,11))
unittest(place,datetime.date(2007,11,3))
unittest(place,datetime.date (2007,11,4))
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 could use within either the client or backend.
What makes it tricky is the hour doesn't necessarily define if it is night and day, this depends pretty much on the year, month, day, hour and geo coordinates.
For clarification... to emulate something like this.
A way to approximate this would be very useful as well.
Hope that someone can help!
You can do as I did and use this public domain Sun.py module to compute the position of the sun relative to positions on the Earth. It's pretty old, but has worked well for me for many years. I made a few superficial modifications to it to be more up-to-date with Python 2.7, such as making the few classes in it new-style, but for the most part it's unchanged.
Here's one module I created, called sunriseset.py, which shows how to use it to calculate the sunrise and sunset times for a specific location given its geographic coordinates and timezone. The referenced timezone
module is an implementation of the tzinfo
abstract base class described in the datetime
module's documentation on tzinfo
objects.
# -*- coding: iso-8859-1 -*-
import datetime
import timezone # concrete tzinfo subclass based on the Python docs
import math
from Sun import Sun
__all__ = ['getsuninfo', 'Place']
class Place(object):
def __init__(self, name, coords, tz=timezone.Pacific):
self.name = name # string
self.coords = coords # tuple (E/W long, N/S lat)
self.tz = tz # tzinfo constant
def _hoursmins(hours):
"""Convert floating point decimal time in hours to integer hrs,mins"""
frac,h = math.modf(hours)
m = round(frac*60, 0)
if m == 60: # rounded up to next hour
h += 1; m = 0
return int(h),int(m)
def _ymd(date):
"""Return y,m,d from datetime object as tuple"""
return date.timetuple()[:3]
def getsuninfo(location, date=None):
"""Return local datetime of sunrise, sunset, and length of day in hrs,mins)"""
if date == None:
querydate = datetime.date.today()
else: # date given should be datetime instance
querydate = date
args = _ymd(querydate) + location.coords
utcrise, utcset = Sun().sunRiseSet(*args)
daylength = Sun().dayLength(*args)
hrs,mins = _hoursmins(daylength)
risehour, risemin = _hoursmins(utcrise)
sethour, setmin = _hoursmins(utcset)
# convert times to timedelta values (ie from midnight utc of the date)
midnight = datetime.datetime(tzinfo=timezone.utc, *_ymd(querydate))
deltarise = datetime.timedelta(hours=risehour, minutes=risemin)
utcdatetimerise = midnight+deltarise
deltaset = datetime.timedelta(hours=sethour, minutes=setmin)
utcdatetimeset = midnight+deltaset
# convert results from UTC time to local time of location
localrise = utcdatetimerise.astimezone(location.tz)
localset = utcdatetimeset.astimezone(location.tz)
return localrise, localset, hrs, mins
if __name__ == "__main__":
import datetime, timezone
def unittest(location, testdate):
risetime, settime, hrs, mins = getsuninfo(location, testdate)
print "Location:", location.name
print "Date:", testdate.strftime("%a %x")
print risetime.strftime("Sunrise %I:%M %p"), settime.strftime("- Sunset %I:%M %p (%Z)")
print "daylight: %d:%02d" % (hrs,mins)
print
place = Place("My House", (-121.990278, 47.204444), timezone.Pacific)
# test dates just before and after DST transitions
print "pre 2007"
print "========="
unittest(place, datetime.date(2006, 4, 1))
unittest(place, datetime.date(2006, 4, 2))
unittest(place, datetime.date(2006, 10, 28))
unittest(place, datetime.date(2006, 10, 29))
print "2007"
print "========="
unittest(place, datetime.date(2007, 3, 10))
unittest(place, datetime.date(2007, 3, 11))
unittest(place, datetime.date(2007, 11, 3))
unittest(place, datetime.date(2007, 11, 4))
这篇关于Javascript或Python - 我如何确定它是夜晚还是白天?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!