13ca350
13ca350

Reputation: 1

How to append current date and time to file name?

I have a script to download a PDF from the internet and save it to a specific directory, how can I go about appending the date and time to the file name?

# Import all needed modules and tools
from fileinput import filename
import os
import os.path
from datetime import datetime
import urllib.request
import requests

# Disable SSL and HTTPS Certificate Warnings
import urllib3
urllib3.disable_warnings()
resp = requests.get('url.org', verify=False)

# Get current date and time
current_datetime = datetime.now()
print("Current date & time : ". current_datetime)

# Convert datetime obj to string
str_current_datetime = str(current_datetime)

# Download and name the PDF file from the URL
response= urllib.request.urlretrieve('url.pdf',
filename = 'my directory\civil.pdf')

# Save to the preferred directory
with open("my directory\civil.pdf", 'wb') as f: f.write(resp.content)

Upvotes: 0

Views: 951

Answers (1)

aanginer
aanginer

Reputation: 130

Use f-strings:

open(f"file - {datetime.now().strftime('%Y-%m-%D')}.txt", "w")
# will create a new file with the title: "file - Year-Month-Date.txt"
# then you can do whatever you want with it

f-string docs

Upvotes: 1

Related Questions