转换(YYYY-MM-DD-HH:MM:SS)日期时间 [英] Converting (YYYY-MM-DD-HH:MM:SS) date time
问题描述
我想将这样的字符串转换为更有用的 29-Apr-2013-15:59:02
。
I want to convert a string like this "29-Apr-2013-15:59:02"
into something more usable.
破折号可以很容易地用空格或其他字符替换。此格式非常理想: YYYYMMDD HH:mm:ss(20130429 15:59:02)
。
The dashes can be easily replaced with spaces or other characters. This format would be ideal: "YYYYMMDD HH:mm:ss (20130429 15:59:02)"
.
编辑:
对不起,我没有在其他帖子中具体看到答案。但是,我还是很无知,所以本可以一直在寻找解决方案,却不知道。我已经做到了,但我不会认为它漂亮。
Sorry, I did not specifically see the answer in another post. But again, I'm ignorant so could have been looking at the solution and didn't know it. I've got this working, but I wouldn't consider it "pretty."
#29-Apr-2013-15:59:02
import sys, datetime, time
#inDate = sys.argv[1]
inDate = 29-Apr-2013-15:59:02
def getMonth(month):
monthDict = {'Jan':'01','Feb':'02','Mar':'03','Apr':'04','May':'05','Jun':'06','Jul':'07','Aug':'08','Sep':'09','Oct':'10','Nov':'11','Dec':'12'}
for k, v in monthDict.iteritems():
if month == k:
return v
day = inDate[:2]
#print day
month = inDate[3:6]
#print month
year = inDate[7:11]
#print year
time = inDate[-8:]
#print time
newDate = year+getMonth(month)+day
newDateTime = newDate+" "+time
print newDate
print newDateTime
是否有改进的想法?
推荐答案
使用datetim e.strptime()将 inDate
字符串解析为日期对象,请使用 datetime.strftime()以您喜欢的任何格式输出:
Use datetime.strptime() to parse the inDate
string into a date object, use datetime.strftime() to output in whatever format you like:
>>> from datetime import datetime
>>> inDate = "29-Apr-2013-15:59:02"
>>> d = datetime.strptime(inDate, "%d-%b-%Y-%H:%M:%S")
>>> d
datetime.datetime(2013, 4, 29, 15, 59, 2)
>>> d.strftime("YYYYMMDD HH:mm:ss (%Y%m%d %H:%M:%S)")
'YYYYMMDD HH:mm:ss (20130429 15:59:02)'
这篇关于转换(YYYY-MM-DD-HH:MM:SS)日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!