問題描述
我正在使用 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"
. (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")
但這不起作用.我得到的錯誤是:
but this does not work. The error I get is:
AttributeError: 'module' 對象沒有屬性 'strptime'
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 在這個簡單的例子中不起作用?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!