为什么datetime.strptime在这个简单的例子中不起作用? [英] Why is datetime.strptime not working in this simple example?
问题描述
我正在使用 strptime 将日期字符串转换为 datetime
。根据链接页面,这样的格式应该可以工作:
I'm using strptime to convert a date string into a datetime
. According to the linked page, formatting like this should work:
>>> # Using datetime.strptime()
>>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
我的代码是:
import datetime
dtDate = datetime.strptime(sDate,"%m/%d/%Y")
其中 sDate =07/27/2012
(例如)。 (我明白,从同一页面来看,%Y
是年份以十进制数字表示。)
where sDate = "07/27/2012"
(for example). (I understand, from the same page, that %Y
is "Year with century as a decimal number.")
我已经尝试将sDate的实际值放入代码中:
I have tried putting the actual value of sDate into the code:
dtDate = datetime.strptime("07/27/2012","%m/%d/%Y")
但这不行。我得到的错误是: AttributeError:'module'对象没有属性'strptime'
but this does not work. The error I get is: AttributeError: 'module' object has no attribute 'strptime'
我做错了什么?
推荐答案
您应该使用 datetime.datetime.strptime
。请注意,旧版本的Python(2.4及更旧版本)没有 datetime.datetime.strptime
;在这种情况下,请使用 time.strptime
。
You should be using datetime.datetime.strptime
. Note that very old versions of Python (2.4 and older) don't have datetime.datetime.strptime
; use time.strptime
in that case.
这篇关于为什么datetime.strptime在这个简单的例子中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!