Pandas: 将日期时间戳转换为白天还是晚上?
Pandas: convert datetime timestamp to whether it's day or night?
我正在尝试根据时间戳列表确定是白天还是晚上。如果我只检查7:00AM到6:00PM之间的小时将其归类为"day",否则是否正确?就像我在下面的代码中所做的那样。我不确定这一点,因为有时甚至在下午 6 点之后也是白天,所以使用 python 区分白天或黑夜的准确方法是什么?
sample data: (timezone= utc/zulutime)
timestamps = ['2015-03-25 21:15:00', '2015-06-27 18:24:00', '2015-06-27 18:22:00', '2015-06-27 18:21:00', '2015-07-07 07:53:00']
Code:
for timestamp in timestamps:
time = datetime.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S")
hr, mi = (time.hour, time.minute)
if hr>=7 and hr<18: print ("daylight")
else: print ("evening or night")
sample output:
evening or night
evening or night
evening or night
evening or night
daylight
不幸的是python的timestamp
无法确定现在是白天还是晚上。这也是因为它取决于您所在的位置以及您如何准确定义白天和黑夜。恐怕你将不得不为此获得辅助数据。
您可以使用 pyephem
完成此任务。这是一个
Python package for performing high-precision astronomy computations.
您可以设置所需的位置并获取太阳高度角。夜晚有多种定义,具体取决于它是用于民用 (-6°)、航海 (-12°) 还是天文 (-18°) 目的。选一个门槛:太阳在下面,就是晚上!
#encoding: utf8
import ephem
import math
import datetime
sun = ephem.Sun()
observer = ephem.Observer()
# ↓ Define your coordinates here ↓
observer.lat, observer.lon, observer.elevation = '48.730302', '9.149483', 400
# ↓ Set the time (UTC) here ↓
observer.date = datetime.datetime.utcnow()
sun.compute(observer)
current_sun_alt = sun.alt
print(current_sun_alt*180/math.pi)
# -16.8798870431°
您需要知道纬度和经度。事实上,如果一个地方在深谷里,日出就会晚,日落就会早。如果您每天需要多次获取此服务,或者只是像 https://www.timeanddate.com/worldclock/uk/london.
中的那样简单地抓取页面,则可以付费购买此服务。
作为解决方法,穆斯林可以免费 api 宣誓时间。它包括准确的日落和日出时间。但是,您仍然需要位置坐标来获取数据。目前免费。
我正在尝试根据时间戳列表确定是白天还是晚上。如果我只检查7:00AM到6:00PM之间的小时将其归类为"day",否则是否正确?就像我在下面的代码中所做的那样。我不确定这一点,因为有时甚至在下午 6 点之后也是白天,所以使用 python 区分白天或黑夜的准确方法是什么?
sample data: (timezone= utc/zulutime)
timestamps = ['2015-03-25 21:15:00', '2015-06-27 18:24:00', '2015-06-27 18:22:00', '2015-06-27 18:21:00', '2015-07-07 07:53:00']
Code:
for timestamp in timestamps:
time = datetime.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S")
hr, mi = (time.hour, time.minute)
if hr>=7 and hr<18: print ("daylight")
else: print ("evening or night")
sample output:
evening or night
evening or night
evening or night
evening or night
daylight
不幸的是python的timestamp
无法确定现在是白天还是晚上。这也是因为它取决于您所在的位置以及您如何准确定义白天和黑夜。恐怕你将不得不为此获得辅助数据。
您可以使用 pyephem
完成此任务。这是一个
Python package for performing high-precision astronomy computations.
您可以设置所需的位置并获取太阳高度角。夜晚有多种定义,具体取决于它是用于民用 (-6°)、航海 (-12°) 还是天文 (-18°) 目的。选一个门槛:太阳在下面,就是晚上!
#encoding: utf8
import ephem
import math
import datetime
sun = ephem.Sun()
observer = ephem.Observer()
# ↓ Define your coordinates here ↓
observer.lat, observer.lon, observer.elevation = '48.730302', '9.149483', 400
# ↓ Set the time (UTC) here ↓
observer.date = datetime.datetime.utcnow()
sun.compute(observer)
current_sun_alt = sun.alt
print(current_sun_alt*180/math.pi)
# -16.8798870431°
您需要知道纬度和经度。事实上,如果一个地方在深谷里,日出就会晚,日落就会早。如果您每天需要多次获取此服务,或者只是像 https://www.timeanddate.com/worldclock/uk/london.
中的那样简单地抓取页面,则可以付费购买此服务。作为解决方法,穆斯林可以免费 api 宣誓时间。它包括准确的日落和日出时间。但是,您仍然需要位置坐标来获取数据。目前免费。