Python日期字符串格式

2024-05-19 22:26:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从字符串格式的python日期中删除填充的零:

formatted_date = my_date.strftime("%m/%d/%Y") # outputs something like: 01/01/2013
date_out = formatted_date.replace(r'/0', r'/').replace(r'^0', r'') 

第二次替换不起作用——我得到了2013年1月1日。如果零在字符串开头的旁边,如何匹配它?在


Tags: 字符串datemy格式outoutputssomethingreplace
1条回答
网友
1楼 · 发布于 2024-05-19 22:26:43

.replace()不使用正则表达式。您正在尝试替换文本^0。在

使用str.format()创建不带零填充的日期格式:

'{0.month}/{0.day}/{0.year}'.format(my_date)

避免替换零。在

演示:

^{pr2}$

如果Python是用glibc库编译的,那么您也可以在格式中使用破折号来抑制填充:

my_date.strftime('%-m/%-d/%y')

但那几乎没有便携性。在

相关问题 更多 >