Why is datetime.strptime not working in this simple example?(为什么 datetime.strptime 在这个简单的例子中不起作用?)
问题描述
我正在使用 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 在这个简单的例子中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 datetime.strptime 在这个简单的例子中不起作用?


基础教程推荐
- 对多索引数据帧的列进行排序 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01