retrieve file from s3 python

#931
Raw
Author
Anonymous
Created
Nov. 1, 2023, 1 p.m.
Expires
Never
Size
1.1 KB
Hits
49
Syntax
None
Private
✗ No
import boto3
import datetime

# Initialize a session using Amazon S3
s3 = boto3.client('s3')

# Specify the bucket name and prefix (folder) where your files are located
bucket_name = 'mooh'
prefix = ''

# List objects in the bucket
response = s3.list_objects_v2(Bucket=bucket_name, Prefix=prefix)

# Check if any objects were found
if 'Contents' in response:
    # Find the latest modified object
    latest_object = max(response['Contents'], key=lambda x: x['LastModified'])
    
    # Get the current time
    current_time = datetime.datetime.now(latest_object['LastModified'].tzinfo)
    
    # Calculate the time difference in hours
    time_difference_hours = (current_time - latest_object['LastModified']).total_seconds() / 3600

    if time_difference_hours <= 14:
        # File is not older than 14 hours, you can return its details or download it
        print(f"Latest File: {latest_object['Key']}")
    else:
        print("File is older than 14 hours, returning null or performing other actions.")
else:
    print("No files found in the bucket.")