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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:13:09  来源:igfitidea点击:

Converting (YYYY-MM-DD-HH:MM:SS) date time

pythondatetimetime

提问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

回答by Dave

You want to look into datetime, in particular strptime.

你要研究一下datetime,特别是strptime