Comparing time in Python

时间:2016-07-11 19:03:50

标签: python python-2.7

My current project is scraping weather data from websites for calculation. Part of this calculation involves different logic depending on if the current time is before or after noon.

import pandas as pd
from bs4 import BeautifulSoup
import requests
import numpy as np  

# Arkansas State Plant Board Weather Web data
url1 = "http://170.94.200.136/weather/Inversion.aspx"
response1 = requests.get(url1)

soup1 = BeautifulSoup(response1.content)
table1 = soup1.find("table", id="MainContent_GridView1")

data1 = pd.read_html(str(table1),header=0)[0] 
data1.columns = ['Station', 'Low Temp (F)', 'Time of Low', 'Current Temp (F)', 'Current Time',  'Wind Speed (MPH)', 'Wind Dir', 'High Temp (F)', 'Time Of High']

print(url1)
print(data1[0:4])

array1 = np.array(data1[0:4])

This is my code to bring in the data I need. However, I don't know how to compare the current time I request as a Unicode string to see if it is before or after noon. Can anyone help me with this?

Edit: some data from the current request

    Station  Low Temp (F) Time of Low  Current Temp (F) Current Time  \
0  Arkansas          69.0     5:19 AM              88.7      2:09 PM   
1    Ashley          70.4     4:39 AM              91.2      2:14 PM   
2   Bradley          69.4     4:09 AM              90.6      2:14 PM   
3    Chicot         -40.2     2:14 PM             -40.2      2:14 PM   

   Wind Speed (MPH)  Wind Dir  High Temp (F) Time Of High  
0               4.3       213           88.9      2:04 PM  
1               4.1       172           91.2      2:14 PM  
2               6.0       203           90.6      2:09 PM  
3               2.2       201          -40.1     12:24 AM  

2 个答案:

答案 0 :(得分:3)

Just check if the meridian is PM or AM.

 time = "2:09 PM"
 meridian = time.split(' ')[-1] # get just the meridian
 before_noon = meridian == 'AM'
 after_noon = meridian == 'PM'

答案 1 :(得分:0)

You can do it like this:

t = pd.to_datetime(data1['Current Time'][0:1][0])
noon = pd.to_datetime("12:00 PM")
if t < noon:
    print("yes")
else:
    print("no")

>>> no
t
>>> Timestamp('2016-07-11 14:04:00')
noon
>>> Timestamp('2016-07-11 12:00:00')