简体   繁体   中英

Sqlite3 naming db file with a variable in python

How can I use the current date to name my db file so when it runs it creates a db file which is named after the current date. This is what I have so far:

import sqlite3
import time


timedbname = time.strftime("%d/%m/%Y")

# Connecting to the database file
conn = sqlite3.connect(???)

with this error its the same with '/' or '-' or '.' in "%d/%m/%Y":

conn = sqlite3.connect(timedbname, '.db')
TypeError: a float is required
27.01.2016

Try using:

time.strftime("%d-%m-%Y")

I guess it doesn't work because of the slashes in the generated date.

You can't have dashes in your table name. Also it can't start with a digit.

import sqlite3
from datetime import date

timedbname = '_' + str(date.today()).replace('-','_')

# Connecting to the database file
conn = sqlite3.connect(':memory:')
cursor = conn.cursor()

cursor.execute('''CREATE TABLE %s (col1 int, col2 int)''' % (timedbname))
cursor.execute('''INSERT INTO %s VALUES (1, 2)''' % (timedbname))
cursor.execute('''SELECT * FROM %s'''%timedbname).fetchall()

This worked:

import sqlite3
import time


timedbname = time.strftime("_" + "%d.%m.%Y")
conn = sqlite3.connect(timedbname + '.db')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM