去掉 Python 中日期字符串的前导零?
有没有一种灵活的方法可以去掉Python中日期字符串的前导零?
在下面的示例中,我希望获得 12/1/2009 作为回报,而不是 12/01/2009。我想我可以使用正则表达式。但对我来说,这似乎有点矫枉过正。有更好的解决方案吗?
>>> time.strftime('%m/%d/%Y',time.strptime('12/1/2009', '%m/%d/%Y'))
'12/01/2009'
参见
Is there a nimble way to get rid of leading zeros for date strings in Python?
In the example below I'd like to get 12/1/2009 in return instead of 12/01/2009. I guess I could use regular expressions. But to me that seems like overkill. Is there a better solution?
>>> time.strftime('%m/%d/%Y',time.strptime('12/1/2009', '%m/%d/%Y'))
'12/01/2009'
See also
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一个更简单易读的解决方案是自己格式化它:
A simpler and readable solution is to format it yourself:
@OP,做一些字符串操作并不需要太多。
@OP, it doesn't take much to do a bit of string manipulation.
我建议使用一个非常简单的正则表达式。这并不是说这对性能至关重要,是吗?
搜索
\b0
并替换为任何内容。IE。:
I'd suggest a very simple regular expression. It's not like this is performace-critical, is it?
Search for
\b0
and replace with nothing.I. e.:
但是,我怀疑这取决于系统的
strftime()
实现,并且可能无法完全移植到所有平台(如果这对您很重要)。However, I suspect this is dependent on the system's
strftime()
implementation and might not be fully portable to all platforms, if that matters to you.