在DD / MM / YYYY和YYYY-MM-DD之间转换日期? [英] Converting date between DD/MM/YYYY and YYYY-MM-DD?

查看:377
本文介绍了在DD / MM / YYYY和YYYY-MM-DD之间转换日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Python脚本,我需要读取一个日期格式为DD / MM / YYYY的CVS文件,并将其转换为YYYY-MM-DD,然后再将其保存到SQLite数据库中。

Using a Python script, I need to read a CVS file where dates are formated as DD/MM/YYYY, and convert them to YYYY-MM-DD before saving this into a SQLite database.

这几乎可行,但是失败了,因为我没有提供时间:

This almost works, but fails because I don't provide time:

from datetime import datetime

lastconnection = datetime.strptime("21/12/2008", "%Y-%m-%d")

#ValueError: time data did not match format:  data=21/12/2008  fmt=%Y-%m-%d
print lastconnection

我认为datetime对象中有一个方法可以非常轻松地执行此转换,但是我找不到如何执行此转换的示例。谢谢。

I assume there's a method in the datetime object to perform this conversion very easily, but I can't find an example of how to do it. Thank you.

推荐答案

您的示例代码有误。可行:

Your example code is wrong. This works:

import datetime

datetime.datetime.strptime("21/12/2008", "%d/%m/%Y").strftime("%Y-%m-%d")

对strptime()的调用将根据第二个参数中指定的格式来解析第一个参数,因此这两个参数需要匹配。然后,您可以调用strftime()将结果格式化为所需的最终格式。

The call to strptime() parses the first argument according to the format specified in the second, so those two need to match. Then you can call strftime() to format the result into the desired final format.

这篇关于在DD / MM / YYYY和YYYY-MM-DD之间转换日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆