【问题标题】:Converting a string to datetime in python [duplicate]在python中将字符串转换为日期时间[重复]
【发布时间】:2011-10-06 03:06:59
【问题描述】:

可能重复:
Parse date and format it using python?

我有一个日期字符串,例如 2011-07-15 13:00:00+00:00 。有什么方法可以将此字符串转换为 python 中的日期时间对象?

谢谢

【问题讨论】:

标签: python datetime


【解决方案1】:

如果您使用dateutil.parser,您可以适当地处理时区,并自动识别格式,如here 所述:

from dateutil import parser
dt = parser.parse("2011-07-15 13:00:00+00:00")

【讨论】:

    【解决方案2】:

    您可以在 datetime 模块中使用 strptime 函数。 http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior

    datetime.datetime.strptime('2011-07-15 13:00:00', '%Y-%m-%d %H:%M:%S')
    

    编辑:

    经验教训,datetime 模块无法做到这一点,至少在我的平台上是这样。根据http://wiki.python.org/moin/WorkingWithTime,Mu Mind 的解决方案似乎是最简单的方法。

    【讨论】:

    • 你能举个例子吗,比如考虑上面的字符串。谢谢:)
    • 感谢您在我执行 datetime.datetime.strptime('2011-07-15 13:00:00+00:00', '%Y-%m-%d %H: %M:%S') 我得到 'ValueError: unconverted data still: +00:00' :( 。我的格式字符串有错误吗?
    • dateutil.parser 为我工作。我没有成功使用strptime。它似乎无法在 Windows XP 上运行?
    猜你喜欢
    • 2016-07-30
    • 2011-07-10
    • 1970-01-01
    • 2012-09-22
    • 1970-01-01
    • 1970-01-01
    • 2015-03-24
    • 2016-05-03
    相关资源
    最近更新 更多