Python 如何将日期字符串转换为不同的格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14524322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a date string to different format
提问by Chamith Malinda
I need to convert date string"2013-1-25" to string"1/25/13" in python.
I looked at the datetime.strptimebut still can't find a way for this.
我需要在python中将日期字符串“2013-1-25”转换为字符串“1/25/13”。我看了看,datetime.strptime但仍然找不到办法。
采纳答案by eumiro
I assume I have import datetimebefore running each of the lines of code below
我假设我import datetime在运行下面的每一行代码之前
datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')
prints "01/25/13".
打印"01/25/13"。
If you can't live with the leading zero, try this:
如果你不能忍受前导零,试试这个:
dt = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print '{0}/{1}/{2:02}'.format(dt.month, dt.day, dt.year % 100)
This prints "1/25/13".
这打印"1/25/13".
EDIT: This may not work on every platform:
编辑:这可能不适用于每个平台:
datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

