python将字符串时间转换为sql datetime格式

时间:2016-09-20 19:30:46

标签: python mysql datetime

我正在将大型csv文件导入ETL到数据库中,并且最初在csv文件中设置的日期格式类似于4/22/2016 1:00:00 PM。每个日期都是较大列表的一部分,其中可能包含非日期类型的项目。例如:

v = ['4/29/2016 8:25:58 AM', '5/25/2016 2:22:22 PM', 'True', 'Foo', 1]

我想用正确的MySQL格式

重新格式化每个日期(如果在列表中)

%m-%d-%Y %I:%M:%S

如何使用列表理解执行此操作?我的代码没有明显的原因,但我不知道从哪里开始。我需要保留在v中找到日期的索引。

from datetime import datetime, date, time

v = ['4/29/2016 8:25:58 AM', '5/25/2016 2:22:22 PM', 'True', 'Foo', 1]


def fixdate(_params):
        tstamp = datetime.strptime(_params, "%m/%d/%Y %I:%M:%S %p")
        newtstamp = date.strftime(tstamp, "%m-%d-%Y %I:%M:%S")
        replace = { _params: newtstamp }
        l = [replace.get(x, x) for x in _params]
        print l


fixdate(v)

1 个答案:

答案 0 :(得分:2)

请检查一下。 注释内嵌代码。

from datetime import datetime

v = ['4/29/2016 8:25:58 AM', '5/25/2016 2:22:22 PM', 'True', 'Foo', 1]

def fixdate(_params):

        print "Before changing format ..."
        print _params
        #First date in list
        tstamp = datetime.strptime(_params[0], "%m/%d/%Y %I:%M:%S %p")
        #Add %p after %S if AM or PM is required
        newtstamp = datetime.strftime(tstamp, "%m-%d-%Y %I:%M:%S")
        #Update the element in list
        _params[0] = newtstamp

        #Second date in list
        tstamp = datetime.strptime(_params[1], "%m/%d/%Y %I:%M:%S %p")
        newtstamp = datetime.strftime(tstamp, "%m-%d-%Y %I:%M:%S")
        #Update the element in list
        _params[1] = newtstamp

        print "After changing format..."
        print _params

fixdate(v)

<强>输出:

C:\Users\dinesh_pundkar\Desktop>python c.py
Before changing format ...
['4/29/2016 8:25:58 AM', '5/25/2016 2:22:22 PM', 'True', 'Foo', 1]
After changing format...
['04-29-2016 08:25:58', '05-25-2016 02:22:22', 'True', 'Foo', 1]

C:\Users\dinesh_pundkar\Desktop>

包含列表理解的代码:

from datetime import datetime

v = ['4/29/2016 8:25:58 AM', '5/25/2016 2:22:22 PM', 'True', 'Foo', 1]

def fixdate(_params):

        print "Before changing format ..."
        print _params

        _params = [i if ':' not in str(i) and '/' not in str(i) else datetime.strftime(datetime.strptime(i, "%m/%d/%Y %I:%M:%S %p"), "%m-%d-%Y %I:%M:%S") for i in _params]

        print "After changing format..."
        print _params

fixdate(v)

<强>输出:

C:\Users\dinesh_pundkar\Desktop>python c.py
Before changing format ...
['4/29/2016 8:25:58 AM', '5/25/2016 2:22:22 PM', 'True', 'Foo', 1]
After changing format...
['04-29-2016 08:25:58', '05-25-2016 02:22:22', 'True', 'Foo', 1]

C:\Users\dinesh_pundkar\Desktop>