Python 转换 (YYYY-MM-DD-HH:MM:SS) 日期时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16286991/
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
Converting (YYYY-MM-DD-HH:MM:SS) date time
提问by dgj32784
I want to convert a string like this "29-Apr-2013-15:59:02"into something more usable.
我想把这样的字符串转换"29-Apr-2013-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)".
破折号可以很容易地替换为空格或其他字符。这种格式将是理想的:"YYYYMMDD HH:mm:ss (20130429 15:59:02)".
Edit:
编辑:
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
Any thoughts on improving?
有什么改进的想法吗?
采纳答案by Bryan
Use datetime.strptime()to parse the inDatestring into a date object, use datetime.strftime()to output in whatever format you like:
使用datetime.strptime()将inDate字符串解析为日期对象,使用datetime.strftime()以您喜欢的任何格式输出:
>>> 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)'
回答by David
Have you investigated dateutil?
你调查过dateutil吗?
http://labix.org/python-dateutil
http://labix.org/python-dateutil
I found a similar question to yours: How do I translate a ISO 8601 datetime string into a Python datetime object?
我发现了一个与您类似的问题: 如何将 ISO 8601 日期时间字符串转换为 Python 日期时间对象?

