pandas :将datetime时间戳转换为白天还是晚上? [英] Pandas: convert datetime timestamp to whether it's day or night?

查看:205
本文介绍了 pandas :将datetime时间戳转换为白天还是晚上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据时间戳列表确定白天还是黑夜.如果我仅检查7:00 AM到6:00 PM之间的时间以将其分类为白天",否则将其分类为夜晚",是否正确?就像我在下面的代码中所做的一样.我不确定这一点,因为有时甚至是下午6点以后的一天,所以使用python区分白天还是晚上的准确方法是什么?

I am trying to determine if its a day or night based on list of timestamps. Will it be correct if I just check the hour between 7:00AM to 6:00PM to classify it as "day", otherwise "night"? Like I have done in below code. I am not sure of this because sometimes its day even after 6pm so whats the accurate way to differentiate between day or night using 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

推荐答案

您可以使用 pyephem .是一个

You could use pyephem for this task. It's a

用于执行高精度天文学计算的Python软件包.

Python package for performing high-precision astronomy computations.

您可以设置所需的位置并获取太阳高度.夜晚有多种定义,取决于它是用于民用(-6°),航海(-12°)还是天文(-18°).只需挑一个要塞:如果太阳在下面,那就是夜间!

You could set the desired location and get the sun altitude. There are multiple definitions for night, depending if it's for civil (-6°), nautical (-12°) or astronomical (-18°) purposes. Just pick a treshold : if the sun is below, it's nighttime!

#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°

这篇关于 pandas :将datetime时间戳转换为白天还是晚上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆