如何将日期字符串转换为不同的格式

Cha*_*nda 82 python

我需要在python中将日期字符串 "2013-1-25" 转换为字符串 "1/25/13".我看了看datetime.strptime但仍然找不到办法.

eum*_*iro 163

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')
Run Code Online (Sandbox Code Playgroud)

打印import datetime.

如果你不能忍受领先的零,试试这个:

dt = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print '{0}/{1}/{2:02}'.format(dt.month, dt.day, dt.year % 100)
Run Code Online (Sandbox Code Playgroud)

这打印"01/25/13".

编辑:这可能不适用于每个平台:

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')
Run Code Online (Sandbox Code Playgroud)

  • 使用`import datetime`. (4认同)

Ale*_*der 20

如果你可以使用01而不是1,那么试试......

d = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print datetime.date.strftime(d, "%m/%d/%y")
Run Code Online (Sandbox Code Playgroud)

您可以查看其他格式指令的文档.