I am new to python and trying to import data from csv file to mysql table. the only issue is all data except datetime is not importing. I am getting all nulls in the datefield, I dont know where i am going wrong.
for row in reader:
print row
try:
(location_id, vrm, start_datetime,end_datetime,ticket_price,crap) = [x.decode('utf-8-sig') for x in row]
except:
print "Error with row: " % row
#sys.exit(3)
tmp = start_datetime.split(" ")
start_date = tmp[0]
start_time = tmp[1]
tmp = end_datetime.split(" ")
end_date = tmp[0]
end_time = tmp[1]
vrm = vrm.replace(' ', '')
vrm = vrm.upper()
tmp = start_date.split('/')
tmp = end_date.split('/')
SessionCost = float(ticket_price)/ 100
iso_date = "%s-%s-%s" %(tmp[0],tmp[1],tmp[2])
entryDatetime = "%s " % iso_date
expiryDatetime = "%s " % iso_date
sql_local = """INSERT INTO customer_1.pay_and_display
(plate, machine_id, ticket_datetime, expiry_datetime, ticket_name, ticket_price)
VALUES ("%s", "%s", "%s", "%s", "%s", "%s") """ % (vrm, location_id, start_datetime,
end_datetime, "IPSWL",SessionCost)
print sql_local
cursor.execute(sql_local)
You could use strptime
import datetime
dt = datetime.datetime.strptime("01/23/2021 04:12:56 AM", '%m/%d/%Y %H:%M:%S %p')
print(dt) #2021-01-23 04:12:56
If your date is using a 12 hour clock, change %H
to %I
Also note that dt
in this example is a date object. Printing it calls it's __str__
(or maybe __repr__
) method. To use it in your SQL you will probably have to do this str(dt)
.
Here is a link to information on the various format characters and their meaning.
If a program I'm working on uses date or time I like to copy and paste this simple block of code. The 'time' variable is a datetime object for the present moment, the 'dtRn' variable makes it easy to display a single string containing datetime. Link to W3Schools Python Datetime Options
import datetime
from time import strftime, strptime
time = datetime.datetime.now()
dtRn = str(strftime("%x") + " " + strftime("%X"))
If you're interested in how long it takes to run a program (start to finish); add a variant of this block of code to the end of the script, and subtract the end time from the start time.
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.