python mysql date,在Python中使用mysql DATE_FORMAT

本文解决了在Python中使用MySQL DATE_FORMAT函数时遇到的问题,通过调整字符串格式化方式避免了Python保留字符冲突,实现了日期格式化的正确应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Hello guys.. I was wondering if any of you tried using DATE_FORMAT in python? you see I''m trying to format one of my field using date_format but the problem is when I try to run it in python it gives an error since % symbol is reserved char for python here is my python codedef get_announcement(con):

try:

c = con.cursor(DictCursor)

query = """

SELECT

id,

page_id,

title,

contents,

bnr_img,

DATE_FORMAT(start_date, ''%M %D, %Y''),

DATE_FORMAT(end_date, ''%M %D, %Y'')

FROM announcement

ORDER BY id DESC;

"""

c.execute(query)

dbres = c.fetchall()

if not dbres: return None

return dbres

finally:

if c: c.close()

But the problem is i cant get this to work since python is complaining about the formatting of the start_date and end_date do you have any idead on how to solve this in a query way. As much as possible I dont want to let python do the date formatting for me instead I want to retrieve the data that has been formatted already in mysql

Please give me your idead and answers thanks and more power

解决方案Never mind guys I already solved it... Just for the record here''s what I came up with

def get_announcement(con):

try:

c = con.cursor(DictCursor)

query = """

SELECT

id,

page_id,

title,

contents,

bnr_img,

DATE_FORMAT(start_date, %s),

DATE_FORMAT(end_date, %s)

FROM announcement

ORDER BY id DESC;

"""

format= "''%M %D, %Y''"

c.execute(query,[format,format])

dbres = c.fetchall()

if not dbres: return None

return dbres

finally:

if c: c.close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值