【问题标题】:How to find out whether it is Day or Night using Timestamp如何使用时间戳确定是白天还是夜晚
【发布时间】:2019-11-07 23:25:46
【问题描述】:

我想从我的数据框中的“时间戳”列中找出是白天还是黑夜。时间戳列的值如下: 20:0、14:30、6:15、5:0、4:0等

我使用了一个 for 循环,但它在白天和黑夜随机生成。

for x in data['timestamp']:
if x> '12:00':
     print('Day')

 else:
     print('Night')

我想要一个列在我的时间戳列旁边,当时间戳在上午 6:00 到 18:00 之间时,它的值为“日”,当时间戳在上午 18:01 到上午 5:59 之间时,它的值为“夜间”。

【问题讨论】:

  • 您不是在比较代码中的时间,而是比较字符串,所以比较是按字母数字顺序进行的。

标签: python pandas datetime timestamp


【解决方案1】:

使用to_timedelta 将值转换为时间增量并通过Series.between 进行比较,然后通过numpy.where 创建新列:

data = pd.DataFrame({
    'timestamp' : ['6:00', '18:00', '18:01', '5:59'],

})

mask = (pd.to_timedelta(data['timestamp'] + ':00')
          .between(pd.Timedelta('6h'),pd.Timedelta('18h')))
data['new'] = np.where(mask, 'Day', 'Night')
print (data)
  timestamp    new
0      6:00    Day
1     18:00    Day
2     18:01  Night
3      5:59  Night

【讨论】:

  • 这不会产生['6:00', '18:00', '18:01', '5:59'] 的预期结果。
  • 嗨,14:30 不是“夜晚”,而是白天。我们不能更改条件以将 14:30 或 12:15 或 14:45 显示为 "Day" 吗?
【解决方案2】:

我会考虑小时部分,将其解析为 int,然后检查它是否在 6 到 18 之间:

hour = int(x.split(':'))[0]
if hour >= 6 and hour < 18:
    print('Day')
else:
    print('Night')

【讨论】:

  • 这不完全正确,根据问题,18:00 仍然是白天。
【解决方案3】:
timestamp = ['6:00', '18:00', '18:01', '5:59']
for time in timestamp:
   hourMin = time.split(":")
   hour = int(hourMin[0])
   mint = int(hourMin[1])
   if hour>= 6 and hour <= 18:
       if(hour == 18):
           if(mint > 0):
               print("Night\n")
           else:
               print("Day\n")
       else:
           print("Day\n")
   else:
       print("Night\n")

【讨论】:

    猜你喜欢
    • 2021-12-27
    • 2013-02-09
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多