W. Stephens
W. Stephens

Reputation: 779

Save a file name as "date - backup"

I am currently exporting a table from by Bigquery to G.C.S as another form of a backup. This is the code I have so far that saves the file name as "firebase_connectioninfo.csv".

# Export table to GCS as a CSV

data = 'dataworks-356fa'
destination = 'gs://firebase_results/firebase_backups1/Firebase_ConnectionInfo.csv'

def export_data_to_gcs(data, Firebase_ConnectionInfo, destination):
    bigquery_client = bigquery.Client(data)
    dataset = bigquery_client.dataset('FirebaseArchive')
    table = dataset.table('Firebase_ConnectionInfo')
    job_name = str(uuid.uuid4())

    job = bigquery_client.extract_table_to_storage(
        job_name, table, 'gs://firebase_results/firebase_backups1/Firebase_ConnectionInfo.csv')
    job.source_format = 'CSV'

    job.begin()

    wait_for_job(job)

def wait_for_job(job):
    while True:
        job.reload()
        if job.state == 'DONE':
            if job.error_result:
                raise RuntimeError(job.errors)
            return
        time.sleep(1)

export_data_to_gcs(data, 'Firebase_ConnectionInfo', destination)

I want this file to be named as "thedate_firebase_connectioninfo_backup". How do I add this command in a Python script?

Upvotes: 0

Views: 955

Answers (2)

Cory Madden
Cory Madden

Reputation: 5193

So this is your string:

gs://firebase_results/firebase_backups1/Firebase_ConnectionInfo.csv'

What I would suggest is putting it into its own variable:

filename = 'gs://firebase_results/firebase_backups1/Firebase_ConnectionInfo.csv'

Additionally, we should put in a spot for the date. We can handle formatting the string a couple different ways, but this is my preferred method:

filename = 'gs://firebase_results/firebase_backups1/{date}-Firebase_ConnectionInfo.csv'

We can then call format() on the filename with the date like this:

from datetime import datetime
date = datetime.now().strftime("%M-%D-%Y")
filename.format(date=date)

Another way we could format the string would be the old string formatting style with %. I hate this method, but some people like it. I think it may be faster.

date = datetime.now().strftime("%M-%D-%Y")
filename = 'gs://firebase_results/firebase_backups1/%s-Firebase_ConnectionInfo.csv' % date

Or, you could use the other guy's answer and just add the strings like

"This " + "is " + "a " + "string." 
outputs: "This is a string."

Upvotes: 2

Ilya
Ilya

Reputation: 4689

Try something like this:

import datetime

datestr = datetime.date.today().strftime("%B-%d-%Y")
destination = 'gs://firebase_results/firebase_backups1/' + datestr + '_Firebase_ConnectionInfo.csv'

Upvotes: 1

Related Questions