简体   繁体   中英

Date Time convert from CSV to MySQL

I have a CSV file which i am loading into MySQL DB, one of the fields is DataTime in NTP time format ex: 10:14:18.531 gmt Wed May 15 2013 I want to convert it to an acceptable format to store it in MySQL like 2013-05-15 10:14:18 .

Should i do this to the CSV file before start loading it to MySQL or it can be done while loading the CSV file (to locate the NTP column on CSV file and convert it while loading)

I have been told that this can be done using Python please help.

Thanks in advance.

You can convert your NTP-formatted dates into datetime using strptime function while loading the CSV file:

from datetime import datetime
import MySQLdb


ntp_string = "10:14:18.531 gmt Wed May 15 2013"
ntp_datetime = datetime.strptime(ntp_string, "%H:%M:%S.%f %Z %a %b %d %Y")

db = MySQLdb.connect(host='...', user='...', passwd='...', db='...')
cursor = db.cursor()

cursor.execute('INSERT INTO test (id, mydate) VALUES (%s, %s)', (1, ntp_datetime))

Hope that helps.

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