【问题标题】:Date Time convert from CSV to MySQL日期时间从 CSV 转换为 MySQL
【发布时间】:2013-07-16 09:50:23
【问题描述】:

我有一个 CSV 文件,我正在加载到 MySQL 数据库中,其中一个字段是 NTP 时间格式的 DataTime,例如:10:14:18.531 gmt Wed May 15 2013 我想转换它以可接受的格式将其存储在 MySQL 中,例如 2013-05-15 10:14:18

我应该在开始将其加载到 MySQL 之前对 CSV 文件执行此操作,还是可以在加载 CSV 文件时完成(以在 CSV 文件上找到 NTP 列并在加载时对其进行转换)

有人告诉我,这可以使用 Python 完成,请帮助。

提前致谢。

【问题讨论】:

标签: python mysql datetime


【解决方案1】:

您可以在加载 CSV 文件时使用 strptime 函数将 NTP 格式的日期转换为 datetime

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))

希望对您有所帮助。

【讨论】:

  • 嗨@alecxe,非常感谢您提供有用的信息。我正在将 csv 文件加载到 MySQL 中,并且使用以下脚本成功使用 Python:inline import MySQLdb c = db.cursor() c.execute("load data local infile '/Users/Desktop/dtest.csv' into table tt lines terminated by '\n'") ,我的问题是如何在加载 CSV 文件时使用 datetime.strptime,假设 NTP 字段是 CSV 中的第二个字段文件。干杯
猜你喜欢
  • 1970-01-01
  • 2011-06-12
  • 1970-01-01
  • 2017-01-30
  • 1970-01-01
  • 2011-07-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多