[英]Error when retrieving Date from datetime.date object in Python
I want to retrieve date in the format of "May 01 2009" from datetime.date object. 我想从datetime.date对象中以“ May 01 2009”的格式检索日期。 I have a table stored in MySQL database.
我有一个表存储在MySQL数据库中。 It has Date column, and Time Column separately.
它分别具有日期列和时间列。 Date in table is of the format,
表格中的日期格式为
2009-05-01
I have connected to MySQL server using PyMySQL module, 我已经使用PyMySQL模块连接到MySQL服务器,
conn = pymysql.connect("localhost", "root", "cloudera", "streaming")
cursor = conn.cursor()
sql = "select * from table1 limit 5;"
cursor.execute(sql)
row = cursor.fetchone()
row[0]
Output is, 输出是
datetime.date(2009, 5, 1)
When I try the below command to extract the date in the way I want, 当我尝试以下命令以所需方式提取日期时,
datetime.date.strftime("%b %d %Y", row[0])
I get an error as, 我收到一个错误,
TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'
I just don't get it, when datetime.date object is provided, it raises an error. 我只是不明白,提供datetime.date对象时,它会引发错误。 Can anyone please help me.
谁能帮帮我吗。 Thanks in advance.
提前致谢。
strftime
is a instance method of date
objects, not a separate function: strftime
是date
对象的实例方法,而不是单独的函数:
print(row[0].strftime("%b %d %Y"))
The error message is trying to tell you that you're calling the uninstanced method (descriptor) from the date
class directly, without passing an instance as first parameter. 错误消息试图告诉您,您正在直接从
date
类调用未实例化的方法(描述符),而没有将实例作为第一个参数传递。
For more info check date objects documentation . 有关更多信息,请检查日期对象文档 。
It's a datetime.date object. 这是一个datetime.date对象。 It has a str () method which will solve your problem.
它具有str ()方法,可以解决您的问题。
import datetime
date=datetime.date(2009,5,1)
datetime.date(2009, 5, 1)
str(d)
will result as '2009-05-01' 结果将为“ 2009-05-01”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.