Guest User

Untitled

a guest
Jul 26th, 2023
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.49 KB | None | 0 0
  1. import os
  2. import csv
  3. import pandas as pd
  4. import pytz
  5. from datetime import datetime, timedelta
  6. import requests
  7.  
  8. '''
  9. checking missing data
  10. '''
  11.  
  12. # Define the absolute path to the root directory where the files are located
  13. root_directory_path = "D:/WS/VsCode/AD_DL_CSV/01_DivideData/src_filtered/03_folder_sorting_by_name"
  14.  
  15. def extract_month_from_filename(filename):
  16. parts = filename.split('_')
  17. return int(parts[-1].split('.')[0])
  18.  
  19. def construct_expected_timestamps(month):
  20. year = 2017
  21. start_date = datetime(year, month, 1, 0, 0, 0, tzinfo=pytz.FixedOffset(480))
  22.  
  23. if month == 12:
  24. end_date = datetime(year+1, 1, 1, 0, 0, 0,tzinfo=pytz.FixedOffset(480))
  25. else:
  26. next_month = month + 1
  27. end_date = datetime(year, next_month, 1, 0, 0, 0,tzinfo=pytz.FixedOffset(480))
  28.  
  29. return pd.date_range(start=start_date, end=end_date, freq='5T')
  30.  
  31. def check_timestamp_intervals_and_station_id(csv_file):
  32. month = extract_month_from_filename(csv_file)
  33. expected_timestamps = construct_expected_timestamps(month)
  34.  
  35. df = pd.read_csv(csv_file)
  36. df['Timestamp'] = pd.to_datetime(df['Timestamp'])
  37.  
  38. # Check for missing timestamps
  39. missing_timestamps = expected_timestamps[~expected_timestamps.isin(df['Timestamp'])]
  40.  
  41. return missing_timestamps
  42.  
  43. '''
  44. Fetch Data
  45. '''
  46. def fetch_data(date_time, query_type):
  47. # Query locations
  48. # air-temperature
  49. # relative-humidity
  50. # rainfall
  51. # wind-speed
  52. url = f"https://api.data.gov.sg/v1/environment/{query_type}?date_time={date_time}"
  53.  
  54. response = requests.get(url)
  55. if response.status_code == 200:
  56. return response.json()
  57. elif 500 <= response.status_code < 600:
  58. print(f"{response.status_code}: The server did not respond in time. Retrying...")
  59. return fetch_data(date_time, query_type)
  60. else:
  61. print(f"Failed to fetch data. Status code: {response.status_code}")
  62. return None
  63.  
  64. def export_to_csv(data, filename):
  65. if data is None:
  66. return
  67.  
  68. with open(filename, 'a', newline='') as csvfile:
  69. writer = csv.writer(csvfile)
  70. for item in data['items']:
  71. timestamp = item['timestamp']
  72. readings = item['readings']
  73. for reading in readings:
  74. station_id = reading.get('station_id', 'UNKNOWN')
  75. myValue = reading.get('value', 'NULL')
  76. writer.writerow([timestamp, station_id, myValue])
  77.  
  78.  
  79. def initiate_download(filename, label, formatted_time, query_type):
  80. #TODO: change label
  81.  
  82. with open(filename, 'w', newline='') as csvfile:
  83. writer = csv.writer(csvfile)
  84. writer.writerow(["Timestamp", "Station ID", label])
  85.  
  86. date_time_to_fetch = formatted_time.strftime("%Y-%m-%dT%H:%M:%S")
  87. json_data = fetch_data(date_time_to_fetch, query_type)
  88. if json_data:
  89. export_to_csv(json_data, filename)
  90. print(f"Data for {filename}, {date_time_to_fetch} exported successfully.")
  91.  
  92.  
  93.  
  94. # Loop through each subfolder and its files to process the data
  95. for subfolder in ["windspeed", "airtemperature", "humidity", "rainfall"]:
  96. subfolder_path = os.path.join(root_directory_path, subfolder)
  97. files = os.listdir(subfolder_path)
  98.  
  99. for file in files:
  100. if file.endswith(".csv"):
  101. file_path = os.path.join(subfolder_path, file) # need to append the entire thing
  102. missing = check_timestamp_intervals_and_station_id(file_path)
  103.  
  104.  
  105.  
  106. # Split the file_name at underscores
  107. parts = file.split('_')
  108. # Combine the parts before the second underscore and append ".csv"
  109. new_file_name = '_'.join(parts[:2]) + ".csv"
  110. new_root_path = "D:/WS/VsCode/AD_DL_CSV/01_DivideData/src_filtered/04_dl_missing"
  111. new_file_path = os.path.join( new_root_path, new_file_name)
  112.  
  113. if subfolder == "windspeed":
  114. label = "Wind Speed (knots)"
  115. query_type = "wind-speed"
  116.  
  117. elif subfolder == "rainfall":
  118. label = "Rainfall (mm)"
  119. query_type = "rainfall"
  120.  
  121. elif subfolder == "airtemperature":
  122. label = "Humidity (pct)"
  123. query_type = "relative-humidity"
  124.  
  125. else:
  126. label = "Air Temperature (deg C)"
  127. query_type = "air-temperature"
  128.  
  129. for timestamp in missing:
  130. initiate_download(new_file_path, label, timestamp, query_type)
  131.  
Advertisement
Add Comment
Please, Sign In to add comment