Python 3中的DateTime函数错误

时间:2018-03-02 12:19:18

标签: python mysql python-3.x datetime

我有一个名为'EntryDate'的csv文件,有些字段有日期,有些在mysql中是空的我有一个默认值应设置为'0000-00-00 00:00:00', csv文件中的日期格式为dd / mm / yyyy HH:MM:SS 所以inmy pyhton脚本我已经使用datetime函数将其更改为正确的格式      d = datetime.strptime(row['EntryDate'], '%d/%m/%Y %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')

但我一直收到此错误

ValueError: time data '' does not match format '%d/%m/%Y %H:%M:%S'

我已经搜索了一个解决方案并尝试了许多不同的方法我仍然会收到此错误, 非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

try:
    d = datetime.strptime(row['EntryDate'], '%d/%m/%Y %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')
except ValueError:
    d = '0000-00-00 00:00:00'

可替换地:

if row['EntryDate'].strip() == '':
    d = '0000-00-00 00:00:00'
else:
    d = datetime.strptime(row['EntryDate'], '%d/%m/%Y %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')

更新以根据OP的评论显示为多列执行此操作的一种方法:

columns = ['EntryDate', 'DateDeparture']
for column in columns:
    if row[column].strip() == '':
        d = '0000-00-00 00:00:00'
    else:
        d = datetime.strptime(row[column], '%d/%m/%Y %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')
    # Do something with d here as you'll overwrite it on next iteration of loop.