File size: 3,792 Bytes
1e66e59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
from datetime import datetime, timedelta
import requests
import os
from datetime import datetime


def check_and_download(url, filename):
  """
  Checks if the URL returns a file and downloads it to the specified filename.

  Args:
      url: The URL to check.
      filename: The name of the file to save the downloaded content to.

  Returns:
      True if the file was downloaded, False otherwise.
  """
  try:
    # Send a HEAD request to get the headers without downloading the content
    url = url + filename
    response = requests.head(url) #, headers=headers)

    if response.status_code == 200:
        # Get the file size
        file_size = int(response.headers.get("Content-Length", 0))

        if file_size > 0:
            print(f"File size is : {file_size}")
            # Download the file and save it
            with open(filename, "wb") as f:
                response = requests.get(url, stream=True)
                for chunk in response.iter_content(chunk_size=1024):
                    f.write(chunk)
                print(f"Downloaded file: {filename}")
                return True
        else:
            print(f"File size is zero: {url}")
    else:
      print(f"Error accessing URL: {url} ({response.status_code})")
  except Exception as e:
    print(f"Error downloading file: {e}")
  return False


def generate_filenames_for_hour_range(date, start_hour, end_hour):
    filenames = []
    microseconds_in_second = 1000000  # Total microseconds in a second
    filenames_per_second = 1000

    for hour in range(start_hour, end_hour + 1):
        for microsec in range(0, microseconds_in_second, int(microseconds_in_second / filenames_per_second)):
            for i in range(filenames_per_second):
                # Create datetime object with the specific microsecond within the second
                current_datetime = date.replace(hour=hour, minute=25, second=54, microsecond=microsec + i)

                # Formatting the date according to the required pattern
                formatted_date = current_datetime.strftime("%d%m%Y%H%M%S%f")[:-3][1:]  # Truncate microseconds to 3 digits
                date_str = current_datetime.strftime("%d-%m-%Y")
                formatted_date = formatted_date.replace('20230925','2023925')

                # Generating the filename and adding it to the list
                filename = f"{formatted_date}Bulletin_1.0_Observed Rainfall_{date_str}.pdf"
                filenames.append(filename)

    return filenames

# Rest of the code remains unchanged, using generate_filenames_for_hour_range in download_for_day
def download_for_day_and_hour_range(date, start_hour, end_hour, url):
    try:
        filenames_for_hour_range = list(set(generate_filenames_for_hour_range(date, start_hour, end_hour)))

        for filename in filenames_for_hour_range:
            print(filename)
            if check_and_download(url, filename):
                print(f"Download successful for {filename}")
                break  # Break the loop if file is downloaded successfully
        else:
            print("Download failed for all filenames")

    except Exception as e:
        print(f"Error during download: {e}")

# Example usage with a date, start hour, end hour, and the URL
given_date = datetime(2023, 12, 4)  # Replace with your specific date
given_start_hour = 9  # Replace with your specific start hour
given_end_hour = 9  # Replace with your specific end hour
#url_to_download = "https://www.chennaifloodsdss.in/HomePage/DownloadImagesFromAlert/0"  # Replace with the actual URL
url_to_download = "https://www.chennaifloodsdss.in/HomePage/DownloadImagesFromAlert/Bulletin_1_0_Observed%20Rainfall_04-12-2023?fname="

download_for_day_and_hour_range(given_date, given_start_hour, given_end_hour, url_to_download)