如何将日期字符串转换为不同的格式 [英] How to convert a date string to different format
本文介绍了如何将日期字符串转换为不同的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在 python 中将日期 string "2013-1-25" 转换为 string "1/25/13".我查看了 datetime.strptime
但仍然找不到方法.
I need to convert date string "2013-1-25" to string "1/25/13" in python.
I looked at the datetime.strptime
but still can't find a way for this.
推荐答案
我假设在运行下面的每一行代码之前我已经import datetime
I assume I have import datetime
before running each of the lines of code below
datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')
打印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)
这会打印 "1/25/13"
.
这可能不适用于每个平台:
This may not work on every platform:
datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')
这篇关于如何将日期字符串转换为不同的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文